如何使用 typescript 和 react-chartjs-2 声明插件选项

How to declare plugin options, using typescript and react-chartjs-2

(我刚开始学习打字稿,所以我敢打赌这对任何熟悉打字稿的人来说都是微不足道的)

我有一个包含以下代码的图表(为简洁起见,我进行了删减):

const pieOptions = {
  plugins: {
    datalabels: {
      display: true,
      color: "white",
      formatter: function (value, context) {
        return `${value}%`;
      },
      font: {
        size: "15",
        weight: "bold"
      }
    }
  }
};

export const HaveAdhdPie: React.FC<Props> = () => {
  return (
    <div>
      <Pie type="pie" data={data} options={pieOptions} />
    </div>
  );
};

Typescript 将 options 属性标记为错误:

部分错误信息:

 Types of property 'weight' are incompatible.
              Type 'string' is not assignable to type 'number | "normal" | "bold" | "bolder" | "lighter"'.

index.d.ts(26, 3): The expected type comes from property 'options' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<Pie> & Readonly<ChartComponentProps> & Readonly<...>'

所以我转到 index.d.ts 文件,找到定义 options.plugins 类型的位置:

    // NOTE: declare plugin options as interface instead of inline '{ [plugin: string]: any }'
    // to allow module augmentation in case some plugins want to strictly type their options.
    interface ChartPluginsOptions {
        [pluginId: string]: any;
    }

就我的理解而言,我被困住了。我不认为我可以更改 type.d.ts 文件,而且我不明白上面代码中的注释指示我做什么。

任何人都可以建议 typescript 接受我的代码需要什么吗?

您不需要扩充类型——您只需要提前为选项命名类型即可:

const pieOptions: chartjs.ChartOptions = { ... }

and/or 告诉 TypeScript 粗体字重是一个常量,所以它可以分配给 number | "normal" | "bold" | "bolder" | "lighter" 类型:

weight: "bold" as const,