Chart.js中同时使用cutout选项与plugins出现TypeScript错误
问题重现
使用Chart.js 4.4.3创建环形(doughnut)图表时,同时配置cutout选项和ChartDataLabels插件,TypeScript会抛出错误,提示'cutout'不存在于对应类型中。移除其中任意一项都能消除错误,但需要同时保留两者以满足设计需求。
代码示例:
this.chart = new Chart("myChart", { type: 'doughnut', data: { datasets: [ { label: labeldata, data: realdata, backgroundColor: colordata, }, ] }, plugins: [ChartDataLabels], options: { cutout: 70, plugins: { datalabels: { display: true, borderRadius: 3, color:'white', font: { weight: 'bold', }, } } } });
错误信息:
Type '{ maintainAspectRatio: false; plugins: { legend: { maxWidth: number | undefined; position: "bottom" | "right"; title: { display: boolean; text: string; padding: number; }; display: boolean; labels: { usePointStyle: true; pointStyle: "circle" | "rect"; font: { size: number; }; }; }; tooltip: { callbacks: { label: () => string; }; }; }; cutout: string; }' is not assignable to type '_DeepPartialObject<CoreChartOptions
& ElementChartOptions & PluginChartOptions & DatasetChartOptions & ScaleChartOptions >'.
Object literal may only specify known properties, and 'cutout' does not exist in type '_DeepPartialObject<CoreChartOptions& ElementChartOptions & PluginChartOptions & DatasetChartOptions & ScaleChartOptions >'.
解决方法
问题根源是引入ChartDataLabels后,TypeScript默认使用通用的ChartOptions类型,而非Doughnut图表专属的配置类型,导致cutout这个环形图特有的属性不被识别。以下两种方法可解决该问题:
方案1:给Chart构造函数指定泛型
在创建Chart实例时,明确指定泛型为'doughnut',让TypeScript识别该图表类型的专属配置:
// 手动指定泛型类型为'doughnut' this.chart = new Chart<'doughnut'>("myChart", { type: 'doughnut', data: { datasets: [ { label: labeldata, data: realdata, backgroundColor: colordata, }, ] }, plugins: [ChartDataLabels], options: { cutout: 70, plugins: { datalabels: { display: true, borderRadius: 3, color:'white', font: { weight: 'bold', }, } } } });
方案2:显式使用Doughnut专属配置类型断言
导入DoughnutChartOptions类型,对options进行类型断言,强制TypeScript识别环形图专属配置:
import { Chart, DoughnutChartOptions } from 'chart.js'; import ChartDataLabels from 'chartjs-plugin-datalabels'; // ... this.chart = new Chart("myChart", { type: 'doughnut', data: { datasets: [ { label: labeldata, data: realdata, backgroundColor: colordata, }, ] }, plugins: [ChartDataLabels], options: { cutout: 70, plugins: { datalabels: { display: true, borderRadius: 3, color:'white', font: { weight: 'bold', }, } } } as DoughnutChartOptions // 类型断言为Doughnut专属配置 });
原理说明
Chart.js针对不同图表类型提供了专属的配置类型,当引入第三方插件时,类型推断可能回退到通用类型,导致特定图表的属性无法被识别。通过指定泛型或类型断言,让TypeScript明确使用Doughnut图表的配置类型,就能正确识别cutout这类专属属性。
内容的提问来源于stack exchange,提问作者Anonymous

