7

I have enum:

enum DemoEnum {
    a = 'EnumValueA',
    b = 'EnumValueB'
}

I would like to create type Type = 'EnumValueA' | 'EnumValueB' from my enum values.

How can I do this?

My current state is type of "keys":

type Type = keyof typeof DemoEnum // 'a' | 'b'

For example I would like to use it in my react props.

type Props {
   value: 'EnumValueA' | 'EnumValueB',
}

In case of usage <MyComponent value='EnumValueA'>

type Props {
   value: DemoEnum,
}

I am getting an error Type .. is not assignable to DemoEnum

2
  • 1
    Why do you want this? Can you show some code where such a type is necessary? Depending on the use case, you can just use DemoEnum as the type, since it is a subtype of the union you're looking for. Commented Sep 4, 2020 at 18:42
  • In react props (updated). Commented Sep 4, 2020 at 18:46

2 Answers 2

14

After the Template Literal Types released, you can directly use it to get what you want:

type Enum = `${DemoEnum}` //  "EnumValueA" | "EnumValueB"
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for this! Have been looking for a solution to this. This is the only real answer to the question!
5

Generally enums are meant to shield users from having to care about their particular values. In some sense you should be able to change the actual string/number values and not change the rest of your code. The conventional way to use this in your react component would therefore look like:

type Props = {
    value: DemoEnum
}

<MyComponent value={DemoEnum.a} />

which should compile without error.


On the flip side, if you find yourself caring a lot about the actual string values "EnumValueA" and "EnumValueB", you might consider abandoning enums entirely and just make a plain object for it:

const DemoEnum = {
    a: 'EnumValueA',
    b: 'EnumValueB'
} as const;

and synthesize the types you care about by inspecting it:

type DemoEnumObject = typeof DemoEnum;
type DemoEnum = DemoEnumObject[keyof DemoEnumObject];

type Props = {
    value: DemoEnum
}

which then will work as

<MyComponent value="EnumValueA" />

or as

<MyComponent value={DemoEnum.a} />

Playground link

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.