Enum to String Literal Union
In this approach, the keyof typeof
operator is used to create a union type of string literals from the enum keys.
Example: Consider an enum Color
with values “Red,” “Green,” and “Blue.” The ColorStringLiteral
type, created using keyof typeof Color
, allows variables to take on only valid color options.
enum Color {
Red = "RED",
Green = "GREEN",
Blue = "BLUE",
}
type ColorStringLiteral = keyof typeof Color;
// Usage
let color: ColorStringLiteral = "Red"; // Valid
// The line below would result in a type
// error since "Yellow" is not a member of the enum.
// let invalidColor: ColorStringLiteral = "Yellow";
console.log(color); // "Red"
Output:
Red
How to Create String Literal Union Type From Enum ?
Enum allows us to define a set of named constants and it can be of any type e.g. Numeric, String, etc. and we need to create string literal union type from that enum.
Below are the approaches used to create a string literal union type from an enum:
Table of Content
- Enum to String Literal Union
- Extract Enum Values
- Using Object.values
- Using Generic Function