如何在打字稿中创建枚举值作为类型/接口?

时间:2020-09-04 18:38:01

标签: typescript enums

我有一个枚举:

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

我想从我的枚举值创建type Type = 'EnumValueA' | 'EnumValueB'

我该怎么做?

我当前的状态是“键”的类型:

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

例如,我想在我的反应道具中使用它。

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

如果使用<MyComponent value='EnumValueA'>

type Props {
   value: DemoEnum,
}

我遇到错误Type .. is not assignable to DemoEnum

2 个答案:

答案 0 :(得分:1)

通常enum的意思是使用户不必关心自己的特定值。从某种意义上讲,您应该能够更改实际的字符串/数字值,而不更改其余的代码。因此,在您的react组件中使用此常规方法将如下所示:

type Props = {
    value: DemoEnum
}

<MyComponent value={DemoEnum.a} />

应正确编译。


另一方面,如果您发现自己非常关心实际的字符串值"EnumValueA""EnumValueB",则可以考虑完全放弃enum,而只为它:

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

并通过检查来综合您关心的类型:

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

type Props = {
    value: DemoEnum
}

然后将用作

<MyComponent value="EnumValueA" />

或为

<MyComponent value={DemoEnum.a} />

Playground link

答案 1 :(得分:0)

Template Literal Types 发布后,你可以直接使用它来得到你想要的:

type Enum = `${DemoEnum}` //  "EnumValueA" | "EnumValueB"