union of enum literal value type converse to union literal value type in typescript

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:

  1. Define an Enum that you want to convert to a Union type.
index.ts
enum MyEnum {
    A = "A",
    B = "B",
    C = "C",
}
55 chars
6 lines
  1. Define a type MyEnumKeys that represents the keys of MyEnum using the keyof operator.
index.ts
type MyEnumKeys = keyof typeof MyEnum;
39 chars
2 lines
  1. Define a type alias MyEnumValues that represents the values of MyEnum using the MyEnumKeys type defined above.
index.ts
type MyEnumValues = typeof MyEnum[MyEnumKeys];
47 chars
2 lines
  1. Now you can use MyEnumKeys or MyEnumValues to define a Union type.
index.ts
// Union of Enum keys
type MyEnumUnionKeys = "A" | "B" | "C"  // same as MyEnumKeys

// Union of Enum values
type MyEnumUnionValues = "A" | "B" | "C"  // same as MyEnumValues
175 chars
6 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