This content originally appeared on DEV Community and was authored by Arnaud Leymet
Let's assume we have the following enum:
enum Fruit {
APPLE = 'apple',
BANANA = 'banana',
CHERRY = 'cherry',
}
Get the keys of an enum dynamically
This one needs the use of two type operators: keyof
and typeof
.
type FruitValue = keyof typeof Fruit
// => type FruitValue = "APPLE" | "BANANA" | "CHERRY"
Get the keys of an enum dynamically
This snippet leverages the Template Literal type operator:
type FruitValue = `${Fruit}`
// => type FruitValue = "apple" | "banana" | "cherry"
Iterate over an enum keys
Looping through the enum keys is as simple as:
for (let fruit of Object.keys(Fruit)) {
console.log(fruit)
}
// => APPLE
// BANANA
// CHERRY
Iterate over an enum values
In the same spirit, looping through the enum values:
for (let fruit of Object.values(Fruit)) {
console.log(fruit)
}
// => apple
// banana
// cherry
This content originally appeared on DEV Community and was authored by Arnaud Leymet
Arnaud Leymet | Sciencx (2021-07-27T16:06:10+00:00) Mastering Enums in TypeScript. Retrieved from https://www.scien.cx/2021/07/27/mastering-enums-in-typescript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.