plugins.legend.align are incompatible types typescript chartjs
Asked Answered
C

3

5

I have something like this in my options object

const options = {
  plugins: {
    legend: {
      align: 'end',
    }
  }
}

According to Chartjs documentation, align accepts 3 values:

  • start
  • center
  • end

The alignment works fine, I am getting the desired result but typescript is complaining that the type of align should be 'start', 'center' or 'end' and not a string.

Type 'string' is not assignable to type ' "end" | "start" | "center" | undefined '

Diving in into Chartjs type definition, I see

export interface LegendOptions<TType extends ChartType> {
  ....
  /**
   * Alignment of the legend.
   * @default 'center'
   */
  align: 'start' | 'center' | 'end';

}

If I change align to a type of string. The typescript error goes away but I shouldn't be doing it.

Any ideas / comments / suggestions is highly appreciated, thanks!

Contrite answered 2/11, 2021 at 10:37 Comment(3)
Cant seem to reproduce it: typescriptlang.org/play?#code/…Subterfuge
Give me a minute pleaseContrite
codesandbox.io/s/modest-lewin-srjyy?file=/src/App.tsxContrite
S
2

Issue seems to be within the react-chartjs-2 lib.

If you switch to the barebone version of chart.js you wont have this issue:https://codesandbox.io/s/goofy-curie-eyxrr?file=/src/App.tsx

Subterfuge answered 2/11, 2021 at 12:52 Comment(0)
F
4

Try add as cons.

align: 'center' as const

Found this solution in their repo

Frayne answered 30/5, 2023 at 7:55 Comment(1)
This works for me!Microbiology
S
2

Issue seems to be within the react-chartjs-2 lib.

If you switch to the barebone version of chart.js you wont have this issue:https://codesandbox.io/s/goofy-curie-eyxrr?file=/src/App.tsx

Subterfuge answered 2/11, 2021 at 12:52 Comment(0)
F
0

I find the as const solution too much of a narrow solution to a problem concerning one specific field. You have to understand what's going on with this string compared to the Align type.

When you have your object like you defined, Typescript believes it's "just" yet another string that can change. It's why the as const works. You're basically saying to typescript, "for this value, it won't change, you can consider it as end instead of string. So the type Align = "end" | ... will work.

To me, the as const solution is sub-optimal, because you solve one conflict, and you'll have to fix all the remaining ones by hand.

For example, using a DoughnutChart, you would do...

    const goodOptions: ChartOptions = {
        plugins: {
            legend: {
                align: "end",
            }
        }
    };
    const _greatChart = (
        <Doughnut
            data={{datasets: []}}
            options={goodOptions}
        />
    )

And your options will be properly infered from the get-go.

Forecourt answered 18/4 at 11:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.