typescript/ enums

I have enum:

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

I would like to create type Type = 'EnumValueA' | 'EnumValueB' 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

Generally enum s 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 enum s 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

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

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

暂无
暂无

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

Related Question How to type enum values with TypeScript? How to create a union type from Enum values in TypeScript? Create Typescript Type from Enum values Use Typescript enum values to create new type Why does exporting an interface, enum or type not create a module in TypeScript? how to map enum values to type in typescript How to build a type from enum values in TypeScript? How to get enum values typescript type How to create enum like type in TypeScript? How to create a generic TypeScript interface which matches any type/interface/object with restrictions on types for values inside it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM