kiril
kiril

Reputation: 5202

How to use options in Chart js v3 custom plugin

I'm following the instructions from the official documentation to create a custom plugin.

I'm using TypeScript and React.

Currently, I'm trying with a dummy plugin that logs to console a message. When I define the plugin directly in the chart (inline) it works correctly. But, when I try to include options of the plugin in the options it shows a Typescript Error.

The error reads as follows:

Type '{ pluginPlugin: {}; }' is not assignable to type '_DeepPartialObject<PluginOptionsByType<"line">>'.
  Object literal may only specify known properties, and 'pluginPlugin' does not exist in type '_DeepPartialObject<PluginOptionsByType<"line">>'

I think all my problem is with TypeScript, because If I simply ignore the ts error, I can see the plugin working correctly.

The code of the dummy plugin is as follows

const dummyPlugin = {
    id: 'pluginPlugin',
    afterDraw: function() {
        console.log("afterDraw");
    }
}

An excerpt of the code of the chart where I use the plugin inline is as follows:

const myChart = new Chart(node, {
                type: 'line',
                data: {datasets: [], labels: []},
                plugins: [dummyPlugin],
                options: {}
});

In this case, the plugin logs correctly.

However, when I try to include some options for the plugin, the error mentioned above shows.

const myChart = new Chart(node, {
                type: 'line',
                data: {datasets: [], labels: []},
                plugins: [dummyPlugin],
                options: {
                    plugins: {
                        pluginPlugin: {}
                    }
                }
});

Upvotes: 2

Views: 2775

Answers (1)

LeeLenalee
LeeLenalee

Reputation: 31371

An answer for this can be found in the New Charts section of the docs, you will need to extend the options chart.js provides.

To do this you will need to add a index.d.ts file to your project in which you can add the following:

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

declare module 'chart.js' {
  interface PluginOptionsByType<TType extends ChartType> {
    pluginPlugin?: { // Key is the pluginId
      customOption1?: boolean;
    }; 
  }
}

Edit:

Updated documentation with specific example on how to add types to a custom plugin: https://www.chartjs.org/docs/master/developers/plugins.html#typescript-typings

Upvotes: 2

Related Questions