How to useObject.values in Javascript
This approach utilizes Object.values
to extract the values of the enum and create a string literal union type.
Example: Consider an enum Direction
with values “North,” “South,” “East,” and “West.” The DirectionStringLiteral
type, created using Object.values
, constrains variables to valid direction options.
enum Direction {
North = "NORTH",
South = "SOUTH",
East = "EAST",
West = "WEST",
}
type DirectionStringLiteral =
`${(typeof Direction)[keyof typeof Direction]}`;
// Usage
let direction: DirectionStringLiteral = "North"; // Valid
// The line below would result in a type
// error since "Up" is not a member of the enum.
// let invalidDirection: DirectionStringLiteral = "Up";
console.log(direction); // "North"
Output:
North
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