angulartypescriptchart.jsbar-chartng2-charts

Setting Chart.js scales y title gives compile time error " type '_DeepPartialObject"


I subscribe to data from the backend to fill my charts, when the data is received I would like to set some options so it goes like this:

this.chart.config.options.scales.y.title.display = true;

This give me a TS compile error

Property 'title' does not exist on type '_DeepPartialObject<{ type: "linear"; } & CartesianScaleOptions & { beginAtZero: boolean; suggestedMin?: number; suggestedMax?: number; grace?: string | number; ticks: { format: NumberFormatOptions; precision: number; stepSize: number; count: number; }; }> | ... 4 more ... | _DeepPartialObject<...>'.

I know I can cast it and it works, but is there a better way than having to cast it every time, working code:

(this.chart.config.options.scales.y as CartesianScaleOptions).title.display = true;

Stackblitz that show the error: https://stackblitz.com/edit/stackblitz-starters-bv1b3c


Solution

  • You have to define the type of chart you are using to the class Chart, which has the type definition.

    ...
    export declare class Chart<
      TType extends ChartType = ChartType,
      TData = DefaultDataPoint<TType>,
      TLabel = unknown
    > {
      ...
    

    The valid values for chart type can be found in the source code chart.js - ChartTypeRegistry Source code

    So we input the TType to be 'bar' since we are creating a bar chart here.

    ...
    export class App implements AfterViewInit {
      title = 'chartjs-test';
      chart: Chart<'bar'> = new Chart('test', { // <- changed here!
        type: 'bar',
        data: { labels: [], datasets: [] },
      });
    

    Stackblitz Demo