如何使用 typescript 和 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 属性标记错误

enter image description here

部分错误信息:

 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 文件,而且我不明白上面代码中的注释指示我做什么。

谁能建议打字稿接受我的代码需要什么?

解决方法

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

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

和/或告诉 TypeScript 粗体粗细是一个常数,因此可以将其分配给 number | "normal" | "bold" | "bolder" | "lighter" 类型:

weight: "bold" as const,

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...