javascript - D3, Vue ו-Typescript: איך לתקן שגיאות נפוצות עבור "ציפו לארגומנט אחד, אך התקבלו 0" ו"האובייקט עשוי להיות 'null'"
כתב ויתור: אני חדש ב-TypeScript. אתם מוזמנים לקשר למסמכים כדי לקרוא עוד על זה. בדקתי את השגיאות באופן מבודד (מחוץ להקשר של d3) אך הפתרונות הללו לא פתרו את הבעיה.
יש לי מיקסין:
import Vue from 'vue';
import { Component, Mixin, Mixins } from 'vue-mixin-decorator';
import { Prop } from 'vue-property-decorator';
import CoreMixin from './core';
import * as d3 from 'd3';
@Mixin
export default class BandAxis extends Mixins<CoreMixin>(CoreMixin) {
// relevant props
@Prop({}) private sizeTo!: string;
@Prop({default: () => ( ['one', 'two', 'three'] )}) private labels!: string[];
// lots of other props props
// relevant code
get scale() {
return d3.scaleBand()
.domain(this.labels)
.rangeRound([0, this.width])
.padding(0.1);
}
get axis() {
return d3.axisBottom()
.scale(this.scale)
.ticks(this.labels.length);
}
private bbox() {
const sel = d3.select(`#${this.sizeTo}`);
if (sel.empty()) {
return {
width: 0,
height: 0,
};
} else {
return sel.node().getBoundingClientRect();
}
}
// more stuff that isn't related
}
השימוש בזה נותן לי:
Expected 1 arguments, but got 0.
get axis() {
> return d3.axisBottom()
ו־ :
Object is possibly 'null'.
| };
| } else {
> | return sel.node().getBoundingClientRect();
| ^
| }
| }
יש רעיונות?
תשובה #1
ההודעה הראשונה מציינת שהקריאה ל-d3.axisBottom חסרה ארגומנט. היא מצפה לארגומנט מסוג AxisScale<Domain>.
ההודעה השנייה מזהירה אותך ש-sel יכול להיות null. זה נחשב לשגיאה בעת הידור עם --strictNullChecks (או --strict) מופעל. כדי להתמודד עם זאת, אתה יכול או:
- השבת את
strictNullCheck(לא מומלץ) - הוסף בדיקת
nullעבורsel:if (sel) { /* השתמש ב-sel */ } - השתמש במפעיל האישור של ערך שאינו null:
sel!.node().getBoundingClientRect()