属性 'getLabelForValue' 在 Chart.js 中的类型不存在
Property 'getLabelForValue' does not exist on type in Chart.js
我在 callback
方法中有一个错误
TS2322:... Type `string | number` is not assignable to type `number`. Type `string` is not assignable to type `number`.
如何解决这个问题?
import { ChartOptions } from "chart.js"
const options: ChartOptions = {
responsive: true,
interaction: {
mode: 'index',
intersect: false,
},
elements: {
point: {
radius: 1,
pointStyle: 'circle',
hoverRadius: 2,
hoverBorderWidth: 3,
},
line: {
fill: true,
},
},
scales: {
x: {
ticks: {
// <--------- error is here --------->
callback(val: number, index: number): string {
return index % 2 === 0 ? this.getLabelForValue(val) : '';
},
color: 'red',
maxRotation: 0,
minRotation: 0,
}
}
}
},
C考虑这个例子:
import { ChartOptions } from "chart.js"
const options: ChartOptions = {
responsive: true,
interaction: {
mode: 'index',
intersect: false,
},
elements: {
point: {
radius: 1,
pointStyle: 'circle',
hoverRadius: 2,
hoverBorderWidth: 3,
},
line: {
fill: true,
},
},
scales: {
x: {
ticks: {
callback(val, index): string {
return index % 2 === 0 && typeof val === 'number' ? this.getLabelForValue(val) : '';
},
color: 'red',
maxRotation: 0,
minRotation: 0,
}
}
}
};
问题是回调中的 val
参数可能是一个字符串,而 getLabelForValue
只需要数字。首先,摆脱回调方法中的显式类型并检查 val
是否为 number
我在 callback
方法中有一个错误
TS2322:... Type `string | number` is not assignable to type `number`. Type `string` is not assignable to type `number`.
如何解决这个问题?
import { ChartOptions } from "chart.js"
const options: ChartOptions = {
responsive: true,
interaction: {
mode: 'index',
intersect: false,
},
elements: {
point: {
radius: 1,
pointStyle: 'circle',
hoverRadius: 2,
hoverBorderWidth: 3,
},
line: {
fill: true,
},
},
scales: {
x: {
ticks: {
// <--------- error is here --------->
callback(val: number, index: number): string {
return index % 2 === 0 ? this.getLabelForValue(val) : '';
},
color: 'red',
maxRotation: 0,
minRotation: 0,
}
}
}
},
C考虑这个例子:
import { ChartOptions } from "chart.js"
const options: ChartOptions = {
responsive: true,
interaction: {
mode: 'index',
intersect: false,
},
elements: {
point: {
radius: 1,
pointStyle: 'circle',
hoverRadius: 2,
hoverBorderWidth: 3,
},
line: {
fill: true,
},
},
scales: {
x: {
ticks: {
callback(val, index): string {
return index % 2 === 0 && typeof val === 'number' ? this.getLabelForValue(val) : '';
},
color: 'red',
maxRotation: 0,
minRotation: 0,
}
}
}
};
问题是回调中的 val
参数可能是一个字符串,而 getLabelForValue
只需要数字。首先,摆脱回调方法中的显式类型并检查 val
是否为 number