reactjstypescriptchart.jsreact-chartjs-2

Custom plugin chartAreaBorder is not the right type but it works


This is how i am using the plugin. How to make typescript to shut up about this?

const options: ChartOptions<"line"> = {
plugins: {
      chartAreaBorder: {
        borderColor: gridColor,
        borderWidth: 1,
      }
  }
...other options..
}

This plugin actually works but typescript is saying:

Type '{ chartAreaBorder: { borderColor: string; borderWidth: number; borderDash: never[]; }; 
legend: { labels: { color: string; }; }; 
tooltip: { callbacks: { label: (this: TooltipModel<...>, toolTipItem: TooltipItem<"line">) 
=> string | undefined; }; }; }' 
is not assignable to type '_DeepPartialObject<PluginOptionsByType<"line">>'.

  Object literal may only specify known properties, and 'chartAreaBorder' does not exist
 in type '_DeepPartialObject<PluginOptionsByType<"line">>'.ts(2322)
index.d.ts(2804, 3): The expected type comes from property 'plugins' which is declared here on type
 '_DeepPartialObject<CoreChartOptions<"line"> & ElementChartOptions<"line"> & PluginChartOptions<"line"> 
& DatasetChartOptions<"line"> & ScaleChartOptions<...> & LineControllerChartOptions>'

Also i didn't know how to type arguments in this plugin so i put any:

const chartAreaBorder = {
    id: "chartAreaBorder",
    beforeDraw(chart: any, args: any, options: any) {
      const {
        ctx,
        chartArea: { left, top, width, height },
      } = chart;
      ctx.save();
      ctx.strokeStyle = options.borderColor;
      ctx.lineWidth = options.borderWidth;
      ctx.setLineDash(options.borderDash || []);
      ctx.lineDashOffset = options.borderDashOffset;
      ctx.strokeRect(left, top, width, height);
      ctx.restore();
    },
  };

Solution

  • You need to extend the typing as explained here: https://www.chartjs.org/docs/4.2.0/developers/plugins.html#typescript-typings

    import {ChartType, Plugin} from 'chart.js';
    
    declare module 'chart.js' {
      interface PluginOptionsByType<TType extends ChartType> {
        chartAreaBorder?: {
          borderColor?: string,
          borderWidth?: string
        }
      }
    }