问题描述
(我刚刚开始学习打字稿,所以我敢打赌这对于熟悉打字稿的人来说是微不足道的)
const pieOptions = {
plugins: {
datalabels: {
display: true,color: "white",formatter: function (value,context) {
return `${value}%`;
},font: {
size: "15",weight: "bold"
}
}
}
};
export const HaveAdhdPie: React.FC<Props> = () => {
return (
<div>
<Pie type="pie" data={data} options={pieOptions} />
</div>
);
};
部分错误信息:
Types of property 'weight' are incompatible.
Type 'string' is not assignable to type 'number | "normal" | "bold" | "bolder" | "lighter"'.
index.d.ts(26,3): The expected type comes from property 'options' which is declared here on type 'IntrinsicAttributes & IntrinsicclassAttributes<Pie> & Readonly<ChartComponentProps> & Readonly<...>'
所以我转到 index.d.ts 文件,并找到 options.plugins
类型的定义位置:
// NOTE: declare plugin options as interface instead of inline '{ [plugin: string]: any }'
// to allow module augmentation in case some plugins want to strictly type their options.
interface ChartPluginsOptions {
[pluginId: string]: any;
}
就我的理解而言,我被卡住了。我不认为我可以更改 type.d.ts
文件,而且我不明白上面代码中的注释指示我做什么。
谁能建议打字稿接受我的代码需要什么?
解决方法
您不需要扩充类型——只是您需要提前为选项命名类型:
const pieOptions: chartjs.ChartOptions = { ... }
和/或告诉 TypeScript 粗体粗细是一个常数,因此可以将其分配给 number | "normal" | "bold" | "bolder" | "lighter"
类型:
weight: "bold" as const,