在 Typescript 中配置 ChartJs 时出现类型错误

Type error when config ChartJs in Typescript

我在 Typescript 中使用 ChartJS 库。 这是我的代码,

const config = {
    type: 'line',
    data: datasets,
    options: {
    }
}


var myChart;
try {
    myChart = new Chart(canvasElm, config)

} catch (error) {
    if (myChart != undefined)
        myChart.destroy();
}

但是我遇到了编译错误:

  TS2345: Argument of type '{ type: string; data: any; options: {}; }' is not assignable to parameter of t
 ype 'ChartConfiguration<"bar" | "line" | "scatter" | "bubble" | "pie" | "doughnut" | "polarArea" | "radar", (n
 umber | ScatterDataPoint | BubbleDataPoint)[], unknown>'.
   Types of property 'type' are incompatible.
     Type 'string' is not assignable to type '"bar" | "line" | "scatter" | "bubble" | "pie" | "doughnut" | "pol
 arArea" | "radar"'.

我使用 put 'line' 作为我的类型。我不确定为什么它没有分配给 type type '"bar" | "line" | "scatter" | "bubble" | "pie" | "doughnut" | "pol arArea" | "radar"'.

Chart 构造函数需要一个有效的配置(ChartConfiguration 类型)。

使用这个类型并尝试满足条件(TypeScript 会知道配置 type 是一个联合)。

import { ChartConfiguration } from "chart.js";

const config: ChartConfiguration = {
  type: 'line',
  data: datasets,
  options: { }
}