diff --git a/website/src/content/docs/faq/typescript.md b/website/src/content/docs/faq/typescript.md index a6fa63324..94f65fe20 100644 --- a/website/src/content/docs/faq/typescript.md +++ b/website/src/content/docs/faq/typescript.md @@ -1,6 +1,6 @@ --- title: "How to use react-chartjs-2 with TypeScript?" -description: "Type the data and options of react-chartjs-2 charts with ChartData, ChartOptions and other types of Chart.js." +description: "Type the data and options of react-chartjs-2 charts with ChartData and ChartOptions, and the options of a custom plugin with PluginOptionsByType." sidebar: order: 9 --- @@ -25,3 +25,40 @@ interface LineProps { The generic type being passed is a `ChartType` that can be one of the following values: `'bar'`, `'line'`, `'scatter'`, `'bubble'`, `'pie'`, `'doughnut'`, `'polarArea'` or `'radar'`. + +## Options of a custom plugin + +Chart.js types `options.plugins` with the `PluginOptionsByType` interface, so TypeScript rejects the options of a plugin it does not know: + +```text wrap +Object literal may only specify known properties, and 'centerText' does not exist in type '_DeepPartialObject>'. +``` + +Add the options of the plugin to the interface with module augmentation, in any module or `.d.ts` file of the project. Then `options.plugins.centerText` type-checks in every chart: + +```typescript +import type { ChartType } from 'chart.js'; + +declare module 'chart.js' { + interface PluginOptionsByType { + centerText?: { + text?: string; + }; + } +} +``` + +The second type parameter of `Plugin` types the options that the hooks of the plugin get: + +```typescript +import type { Plugin } from 'chart.js'; + +const centerText: Plugin<'doughnut', { text?: string }> = { + id: 'centerText', + afterDraw(chart, args, options) { + // options.text is a string or undefined + } +}; +``` + +The whole plugin is in [Why doesn't the chart use new plugins?](/faq/plugins/), and the typings of plugins are in [the Chart.js documentation](https://www.chartjs.org/docs/latest/developers/plugins.html#typescript-typings).