自定义插件chartAreaBorder不是正确的类型,但它可以工作

vwkv1x7d  于 2023-05-28  发布在  Chart.js
关注(0)|答案(1)|浏览(158)

这就是我使用插件的方式。如何让 typescript 闭嘴这件事?

const options: ChartOptions<"line"> = {
plugins: {
      chartAreaBorder: {
        borderColor: gridColor,
        borderWidth: 1,
      }
  }
...other options..
}

这个插件实际上工作,但typescript说:

Type '{ chartAreaBorder: { borderColor: string; borderWidth: number; borderDash: never[]; }; 
legend: { labels: { color: string; }; }; 
tooltip: { callbacks: { label: (this: TooltipModel<...>, toolTipItem: TooltipItem<"line">) 
=> string | undefined; }; }; }' 
is not assignable to type '_DeepPartialObject<PluginOptionsByType<"line">>'.

  Object literal may only specify known properties, and 'chartAreaBorder' does not exist
 in type '_DeepPartialObject<PluginOptionsByType<"line">>'.ts(2322)
index.d.ts(2804, 3): The expected type comes from property 'plugins' which is declared here on type
 '_DeepPartialObject<CoreChartOptions<"line"> & ElementChartOptions<"line"> & PluginChartOptions<"line"> 
& DatasetChartOptions<"line"> & ScaleChartOptions<...> & LineControllerChartOptions>'

我也不知道如何在这个插件类型参数,所以我把任何:

const chartAreaBorder = {
    id: "chartAreaBorder",
    beforeDraw(chart: any, args: any, options: any) {
      const {
        ctx,
        chartArea: { left, top, width, height },
      } = chart;
      ctx.save();
      ctx.strokeStyle = options.borderColor;
      ctx.lineWidth = options.borderWidth;
      ctx.setLineDash(options.borderDash || []);
      ctx.lineDashOffset = options.borderDashOffset;
      ctx.strokeRect(left, top, width, height);
      ctx.restore();
    },
  };
2lpgd968

2lpgd9681#

您需要扩展类型,如下所述:https://www.chartjs.org/docs/4.2.0/developers/plugins.html#typescript-typings

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

declare module 'chart.js' {
  interface PluginOptionsByType<TType extends ChartType> {
    chartAreaBorder?: {
      borderColor?: string,
      borderWidth?: string
    }
  }
}

相关问题