Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在typescript中将枚举值创建为类型/接口?_Typescript_Enums - Fatal编程技术网

如何在typescript中将枚举值创建为类型/接口?

如何在typescript中将枚举值创建为类型/接口?,typescript,enums,Typescript,Enums,我有: enum DemoEnum { a = 'EnumValueA', b = 'EnumValueB' } 我想从我的枚举值创建type='EnumValueA'|'EnumValueB' 我该怎么做 我的当前状态是“密钥”类型: type-type=keyof-typeof-DemoEnum/'a'|'b' 例如,我想在我的react道具中使用它 type Props { value: 'EnumValueA' | 'EnumValueB', } 如果使用 我收

我有:

enum DemoEnum {
    a = 'EnumValueA',
    b = 'EnumValueB'
}
我想从我的枚举值创建
type='EnumValueA'|'EnumValueB'

我该怎么做

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

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

例如,我想在我的react道具中使用它

type Props {
   value: 'EnumValueA' | 'EnumValueB',
}
如果使用


我收到一个错误
类型。。不可分配给DemoEnum

通常
enum
旨在保护用户不必关心其特定值。在某种意义上,您应该能够更改实际的字符串/数字值,而不必更改代码的其余部分。因此,在react组件中使用此功能的传统方式如下所示:

type Props = {
    value: DemoEnum
}

<MyComponent value={DemoEnum.a} />
并通过检查来综合您关心的类型:

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

type Props = {
    value: DemoEnum
}
那么它将作为

<MyComponent value="EnumValueA" />

或作为



您为什么想要这个?你能展示一些需要这样一个类型的代码吗?根据用例的不同,您可以使用
DemoEnum
作为类型,因为它是您正在寻找的联合的子类型。在react props(更新版)中。
type DemoEnumObject = typeof DemoEnum;
type DemoEnum = DemoEnumObject[keyof DemoEnumObject];

type Props = {
    value: DemoEnum
}
<MyComponent value="EnumValueA" />
<MyComponent value={DemoEnum.a} />