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

Viewed 2135

(I've just started learning typescript, so I bet this is trivial for anyone familiar with typescript)

I have a chart with the following code (I've abridged for brevity):

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 flags the options prop as an error: enter image description here

part of the error message:

 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<...>'

So I go to the index.d.ts file, and find where the options.plugins types are defined:

    // 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;
    }

This as far as my understanding goes and I'm stuck. I don't imagine I can change the type.d.ts file and I don't understand what the comments in the above code are directing me to do.

Can anyone please suggest what is required for typescript to accept my code?

1 Answers

You don't need to augment types – it's just that you need to either name the type for the options earlier:

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

and/or tell TypeScript that that bold weight is a constant, so it can be assigned to the number | "normal" | "bold" | "bolder" | "lighter" type:

weight: "bold" as const,
Related