Home > Blockchain >  Can't use Enum value as data of type Enum["A"] | Enum["B"] | etc
Can't use Enum value as data of type Enum["A"] | Enum["B"] | etc

Time:12-14

export enum ChartType {
  Table = 'Table',
  Pie = 'Pie',
  DonutPie = 'DonutPie',
  Column = 'Column',
  Bar = 'Bar',
  Line = 'Line',
  StackedBar = 'StackedBar',
  StackedColumn = 'StackedColumn',
  DonutStat = 'DonutStat',
  HalfDonutStat = 'HalfDonutStat',
  ProgressBarStat = 'ProgressBarStat',
  IconStat = 'IconStat',
  Area = 'Area',
  StackedArea = 'StackedArea',
}

type DataTableChartType = typeof ChartType["Pie"]
  | typeof ChartType["DonutPie"]
  | typeof ChartType["Column"]
  | typeof ChartType["Bar"]
  | typeof ChartType["Line"]
  | typeof ChartType["Area"]
  | typeof ChartType["StackedColumn"]
  | typeof ChartType["StackedBar"]


type ChartOptionType = {
  value: DataTableChartType,
  label: string,
  icon: ReactElement,
}

type AvailableChartsType = {
  [key in DataTableChartType]: ChartOptionType;
};

const AVAILABLE_CHARTS: AvailableChartsType = {
  [ChartType["Pie"]]: {
    value: ChartType["Pie"],           //<------------- error here
    label: 'Pie chart',
    icon: <PieChartIcon width='15' />,
  }
}

I really don't understand why this is happening. Could you please explain?

TS2322: Type 'ChartType' is not assignable to type 'DataTableChartType'.
ChartWidgetToolbar.tsx(69, 3): The expected type comes from property 'value' which is declared here on type 'ChartOptionType'

If I change the data type to string then it works.

Also if I add as DataTableChartType, but I'm wondering why this "cast" is needed?

CodePudding user response:

I'm not exactly sure why this is a problem, but the issue is this line:

[ChartType["Pie"]]: {

If you change it to use dot notation instead of bracket notation, the error goes away:

[ChartType.Pie]: {

(You'll then get another error, which is just pointing out that AVAILABLE_CHARTS needs more than just the pie chart)

Playground Link

  • Related