将图表 js 选项与react-chartjs-2 和 typescript 结合使用

Kyl*_*yle 4 typescript reactjs chart.js react-chartjs

我正在尝试使用带有react-chartjs 圆环图的插件。为了使用该插件(https://www.npmjs.com/package/@scottalan/chartjs-plugin-doughnutlabel),我必须将选项传递给组件。但是当我尝试传递选项时,出现类型错误

Type '{ doughnutlabel: { labels: { text: string; font: { size: string; family: string; style: string; weight: string; }; color: string; }[]; }; }' is not assignable to type '_DeepPartialObject<PluginOptionsByType<keyof ChartTypeRegistry>>'.
  Object literal may only specify known properties, and 'doughnutlabel' does not exist in type '_DeepPartialObject<PluginOptionsByType<keyof ChartTypeRegistry>>'.
Run Code Online (Sandbox Code Playgroud)

我最好的猜测是,这ChartOptions是分配给我的错误类型options,因为我得到了相同的错误事件,而没有尝试将插件与const options: ChartOptions = {}. 我的完整代码如下,感谢任何帮助。

Type '{ doughnutlabel: { labels: { text: string; font: { size: string; family: string; style: string; weight: string; }; color: string; }[]; }; }' is not assignable to type '_DeepPartialObject<PluginOptionsByType<keyof ChartTypeRegistry>>'.
  Object literal may only specify known properties, and 'doughnutlabel' does not exist in type '_DeepPartialObject<PluginOptionsByType<keyof ChartTypeRegistry>>'.
Run Code Online (Sandbox Code Playgroud)

我正在使用react-chartjs-2版本4.0.0和react版本17.0.2。

Kyl*_*yle 7

事实证明,可以通过使用any而不是解决打字错误ChartOptions

const options: any = {
  ...
}
Run Code Online (Sandbox Code Playgroud)

正如 LeeLenalee 指出的那样,将这个特定插件与 Chart.js V3 一起使用也存在问题,但any与另一个类似的插件一起使用时也存在问题。


小智 5

类型从 Chart.js 导出

import type { ChartData, ChartOptions } from 'chart.js';

interface DoughnutProps {
  options: ChartOptions<'doughnut'>;
  data: ChartData<'doughnut'>;
}
Run Code Online (Sandbox Code Playgroud)