To convert an Enum literal value type to a Union literal value type in TypeScript, we can use the keyof
operator along with a type assertion. Here are the steps:
index.ts55 chars6 lines
MyEnumKeys
that represents the keys of MyEnum
using the keyof
operator.index.ts39 chars2 lines
MyEnumValues
that represents the values of MyEnum
using the MyEnumKeys
type defined above.index.ts47 chars2 lines
MyEnumKeys
or MyEnumValues
to define a Union type.index.ts175 chars6 lines
Note that if you add or remove keys from the MyEnum
Enum, the MyEnumKeys
, MyEnumValues
, and MyEnumUnion
types will automatically update to reflect the change.
gistlibby LogSnag