How to useGeneric Function in Javascript
In this approach, we’ll create a generic function enumToLiteralUnion that takes an enum object as input and returns a string literal union type representing its keys. This method enhances reusability and flexibility by allowing the conversion of any enum to a string literal union type.
Example: In this example we defines an enum ‘Fruit’, converts it to a string literal union type using a generic function, and assigns it to a variable ‘fruit’, outputting its values.
enum Fruit {
Apple = "APPLE",
Banana = "BANANA",
Orange = "ORANGE",
}
function enumToLiteralUnion<E extends {
[key: string]: string }>(enumObject: E): keyof E {
return Object.keys(enumObject)[0] as keyof E;
}
// Usage
type FruitLiteralUnion = keyof typeof Fruit;
let fruit: FruitLiteralUnion = enumToLiteralUnion(Fruit);
console.log(fruit);
Output:
Apple
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