属性"getLabelForValue"在图表中的类型上不存在.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,
}
}
}
},

COnsider this example:

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

scales: {
xAxes: [{
gridLines: {
display: false
},
ticks: {
beginAtZero: true,
callback: function(value, index, values) {
return value.substr(0, 12);
},
},
}],

为我工作

最新更新