自定义插件和 afterDraw 回调 Chart.js 和 react-chartjs-2 的 TypeScript 问题

TypeScript issue with custom plugin and afterDraw callback Chart.js and react-chartjs-2

现在推断 chart 的类型,但我想使用正确的类型,而不必解决使用 any 和禁用规则。

  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 */
      },
    },
  ];

您需要从 Chart.js 导入插件接口并输入您的代码:

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();
        }
    }
}];