Extract Enum Values
This approach uses (keyof typeof)
along with & string
to create a string literal union type from the enum.
Example: Consider an enum Size
with values “Small,” “Medium,” and “Large.” The SizeStringLiteral
type, created using (keyof typeof Size) & string
, restricts variables to valid size options.
enum Size {
Small = "SMALL",
Medium = "MEDIUM",
Large = "LARGE",
}
type SizeStringLiteral = (keyof typeof Size) & string;
// Usage
let size: SizeStringLiteral = "Medium"; // Valid
// The line below would result in a type error
// since "ExtraLarge" is not a member of the enum.
// let invalidSize: SizeStringLiteral = "ExtraLarge";
console.log(size); // "Medium"
Output:
Medium
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