How to create enum values as type/interface in typescript?

我们两清 提交于 2021-02-02 09:54:49

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/63746463/how-to-create-enum-values-as-type-interface-in-typescript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!