Home > Software design >  TypeScript issue How to pass parameters in a custom plugin for Chart.js and react-chartjs-2
TypeScript issue How to pass parameters in a custom plugin for Chart.js and react-chartjs-2

Time:08-19

I created a custom plugin horizontalArbitraryLine

import { Plugin } from "chart.js";

export const horizontalArbitraryLine: Plugin = {
    id: "horizontalArbitraryLine",
    beforeDraw(chart, args, options) {
        const {
            ctx,
            chartArea: { top, right, bottom, left, width, height },
            scales: { x, y },
        } = chart;
        ctx.save();
        // console.log(chart, args, options);
        console.log(options.lineColor);
    },
};

I wanted to use horizontalArbitraryLine custom plugin and pass lineColor to it

   options: {
        plugins: {
            legend: {
                position: "bottom",
            },
            horizontalArbitraryLine: {
                lineColor: "black",
            },
        },
    },

encountered the following problem

Type '{ legend: { position: "bottom"; }; horizontalArbitraryLine: { lineColor: string; }; }' is not assignable to type '_DeepPartialObject<PluginOptionsByType<keyof ChartTypeRegistry>>'.
  Object literal may only specify known properties, and 'horizontalArbitraryLine' does not exist in type '_DeepPartialObject<PluginOptionsByType<keyof ChartTypeRegistry>>'.ts(2322)

I thank you in advance for your help.

CodePudding user response:

You need to extend chart.js typings by creating your own index.d.ts file and put the following in it:

import {ChartType, Plugin} from 'chart.js';

declare module 'chart.js' {
  interface PluginOptionsByType<TType extends ChartType> {
    horizontalArbitraryLine?: {
      lineColor: string
    };
  }
}
  • Related