【问题标题】:How to declare plugin options, using typescript and react-chartjs-2如何使用 typescript 和 react-chartjs-2 声明插件选项
【发布时间】:2021-05-14 09:58:30
【问题描述】:

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

我有一个带有以下代码的图表(为简洁起见,我已删节):

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

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

【问题讨论】:

    标签: javascript reactjs typescript react-chartjs-2


    【解决方案1】:

    您不需要增加类型 - 只是您需要在前面为选项命名类型:

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

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

    weight: "bold" as const,
    

    【讨论】:

    • weight: "bold" as const, 成功了。谢谢!我不清楚chartjs.ChartOptions 应该来自什么。我在哪里导入 chartjs 对象?
    • 您的 IDE 应该能够自动导入它,但您应该能够做到,例如import * as chartjs from 'chart.js';...
    • 太棒了。是的,这成功了。我一直在尝试使用 codesandbox,所以它可能会丢失很多功能。
    猜你喜欢
    • 1970-01-01
    • 2017-09-16
    • 2016-07-22
    • 2019-08-09
    • 2020-10-24
    • 1970-01-01
    • 2012-10-25
    • 2022-11-25
    • 1970-01-01
    相关资源
    最近更新 更多