简体   繁体   English

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

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

I have enum:我有枚举:

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

I would like to create type Type = 'EnumValueA' | 'EnumValueB'我想创建type Type = 'EnumValueA' | 'EnumValueB' type Type = 'EnumValueA' | 'EnumValueB' from my enum values. type Type = 'EnumValueA' | 'EnumValueB'来自我的枚举值。

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'>如果使用<MyComponent value='EnumValueA'>

type Props {
   value: DemoEnum,
}

I am getting an error Type .. is not assignable to DemoEnum我收到一个错误Type .. is not assignable to DemoEnum

Generally enum s are meant to shield users from having to care about their particular values.通常enum旨在保护用户不必关心他们的特定值。 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:因此,在您的 React 组件中使用它的传统方法如下所示:

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 enum s entirely and just make a plain object for it:另一方面,如果您发现自己非常关心实际的字符串值"EnumValueA""EnumValueB" ,您可能会考虑完全放弃enum并为其创建一个普通对象:

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 游乐场链接

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM