Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 38 additions & 1 deletion website/src/content/docs/faq/typescript.md
Original file line number Diff line number Diff line change
@@ -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
---
Expand All @@ -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<PluginOptionsByType<"doughnut">>'.
```

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<TType extends ChartType> {
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).