[英]How to create enum values as type/interface in typescript?
我有枚举:
enum DemoEnum {
a = 'EnumValueA',
b = 'EnumValueB'
}
我想创建type Type = 'EnumValueA' | '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
通常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} />
Template Literal Types 发布后,你可以直接使用它来得到你想要的:
type Enum = `${DemoEnum}` // "EnumValueA" | "EnumValueB"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.