2

I have an enum defined as following:

export enum SwitchEnum{
  On = 'ON',
  Off = 'OFF',
}

I want to create a an array of objects from this enum so I tried as following:

export interface SelectProps {
  id: number;
  value: string | number | undefined;
  label: string | undefined;
}

const listItems: SelectProps [] = Object.keys(SwitchEnum).map((key, index) => ({
  id: index,
  value: SwitchEnum[key],
  label: key
}));

But Typescript is complaining with this error:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof SwitchEnum'.
  No index signature with a parameter of type 'string' was found on type 'typeof SwitchEnum'

How can I solve this?

3
  • change [key] to [key as keyof typeof SwitchEnum] Commented Jun 24, 2022 at 10:09
  • @TobiasS. has a point but you could also tweak you value type to accept values of SwitchEnum and therefore avoid casting Commented Jun 24, 2022 at 10:10
  • Does this answer your question? TypeScript TS7015 error when accessing an enum using a string type parameter Commented Jun 24, 2022 at 10:11

1 Answer 1

1

In TypeScript, enums are used as types at compile-time to achieve type-safety for the constants but they are treated as objects at runtime. This is because, they are converted to plain objects once the TypeScript code is compiled to JavaScript. So, the explanation of the objects above is applicable here too. So to fix the typeScript error you should change your code into this:

const listItems: SelectProps [] = Object.keys(SwitchEnum).map((key,index) => ({
 id: index,
 value: SwitchEnum[key as keyof typeof SwitchEnum],
 label: key
}));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.