错误 TS2322:类型“字符串”不可分配给类型“keyof ChartTypeRegistry”

时间:2021-07-04 12:43:55

标签: angular typescript chart.js ng2-charts

home.component.ts

global: boolean = false;
  country!: string;
  data: GlobalData;
  dailyData: any[] = [];
  countries: any[] = [];
  lineChartData: any[] = [
    {
      data: [65, 64, 33, 44],
      label: 'Temp label'
    }
  ];
  lineChartType = "line";
  lineChartLabels: any[] = [
    'label01', 'label02', 'label03'
  ];
  barChartData: any[] = [
    {
      data: [65, 76, 33],
      label: 'Label'
    }
  ];

home.component.html

<canvas baseChart
                [chartType] = "lineChartType"
                [datasets] = "lineChartData"
                [labels] = "lineChartLabels"
            >
            </canvas>
  • 错误:类型“string”不可分配给类型“keyof ChartTypeRegistry”
  • 错误行:[chartType] = "lineChartType"

---在 home.component.html 中发生错误 我需要一个解决方案。尝试在 google 上找到解决方案,但我找不到。

1 个答案:

答案 0 :(得分:1)

仅供参考,ChartTypeRegistry 是由 version 3.0 and later 中的 chart.js 引入的。

因此,我得出结论,您安装的 chart.js 与最新的 ng2-chart(版本 2.4.2)不兼容。

为了重现同样的问题,我安装了 chart.js 3.4 版,链接如下:

Sample project (chart.js v 3.4)


解决方案(chart.js 3.0之前版本)

根据ng2-charts - npm

你需要安装chart.js:

npm install chart.js@2.9.4

npm install @types/chart.js@2.9.33

Sample solution (chart.js v 2.9.4)


解决方案(chart.js 3.0 及更高版本)

使用 lineChartType 类型指定 ChartType

import { ChartType } from 'chart.js';

public lineChartType: ChartType = "line";

Sample solution (chart.js v 3.0)