[SOLVED] Type error when config ChartJs in Typescript

Issue

I am using ChartJS library in Typescript.
Here is my code,

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


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

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

But I am getting compile error:

  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"'.

I use put ‘line’ as my type. I am not sure why it is not assignilbe to type type '"bar" | "line" | "scatter" | "bubble" | "pie" | "doughnut" | "pol arArea" | "radar"'.

Solution

The Chart constructor expects a valid config (of type ChartConfiguration).

Use this type and try to meet the conditions (TypeScript will know the config type is a union).

import { ChartConfiguration } from "chart.js";

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

Answered By – axtck

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *