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
Print
Share
Comment
Cite
Upload
Translate
APA
Arnaud Leymet | Sciencx (2024-03-29T08:42:18+00:00) » Mastering Enums in TypeScript. Retrieved from https://www.scien.cx/2021/07/27/mastering-enums-in-typescript/.
MLA" » Mastering Enums in TypeScript." Arnaud Leymet | Sciencx - Tuesday July 27, 2021, https://www.scien.cx/2021/07/27/mastering-enums-in-typescript/
HARVARDArnaud Leymet | Sciencx Tuesday July 27, 2021 » Mastering Enums in TypeScript., viewed 2024-03-29T08:42:18+00:00,<https://www.scien.cx/2021/07/27/mastering-enums-in-typescript/>
VANCOUVERArnaud Leymet | Sciencx - » Mastering Enums in TypeScript. [Internet]. [Accessed 2024-03-29T08:42:18+00:00]. Available from: https://www.scien.cx/2021/07/27/mastering-enums-in-typescript/
CHICAGO" » Mastering Enums in TypeScript." Arnaud Leymet | Sciencx - Accessed 2024-03-29T08:42:18+00:00. https://www.scien.cx/2021/07/27/mastering-enums-in-typescript/
IEEE" » Mastering Enums in TypeScript." Arnaud Leymet | Sciencx [Online]. Available: https://www.scien.cx/2021/07/27/mastering-enums-in-typescript/. [Accessed: 2024-03-29T08:42:18+00:00]
rf:citation » Mastering Enums in TypeScript | Arnaud Leymet | Sciencx | https://www.scien.cx/2021/07/27/mastering-enums-in-typescript/ | 2024-03-29T08:42:18+00:00
https://github.com/addpipe/simple-recorderjs-demo