'TypeScript issue with custom plugin and afterDraw callback Chart.js and react-chartjs-2
The type for chart is now inferred but I'd like to use a proper type without having to resolve to using any and disabling rules.
const plugins = [
{
id: "tooltipLine",
afterDraw: (chart: { tooltip?: any; scales?: any; ctx?: any }) => {
/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call */
if (chart.tooltip.opacity === 1) {
const { ctx } = chart;
const { caretX } = chart.tooltip;
const topY = chart.scales.y.top;
const bottomY = chart.scales.y.bottom;
ctx.save();
ctx.setLineDash([3, 3]);
ctx.beginPath();
ctx.moveTo(caretX, topY - 5);
ctx.lineTo(caretX, bottomY);
ctx.lineWidth = 1;
ctx.strokeStyle = getRgba(colors.white, 0.5);
ctx.stroke();
ctx.restore();
}
/* eslint-enable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call */
},
},
];
Solution 1:[1]
You need to import the Plugin interface from Chart.js and type your code:
import {
Chart,
Plugin
} from 'chart.js';
const plugins: Plugin[] = [{
id: "tooltipLine",
afterDraw: (chart) => {
if (chart.tooltip.opacity === 1) {
const {
ctx
} = chart;
const {
caretX
} = chart.tooltip;
const topY = chart.scales.y.top;
const bottomY = chart.scales.y.bottom;
ctx.save();
ctx.setLineDash([3, 3]);
ctx.beginPath();
ctx.moveTo(caretX, topY - 5);
ctx.lineTo(caretX, bottomY);
ctx.lineWidth = 1;
ctx.strokeStyle = getRgba(colors.white, 0.5);
ctx.stroke();
ctx.restore();
}
}
}];
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | LeeLenalee |
