An Interest In:
Web News this Week
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
July 27, 2021 04:06 pm GMT
Original Link: https://dev.to/prod/mastering-enums-in-typescript-1c1j
Mastering Enums in TypeScript
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
Original Link: https://dev.to/prod/mastering-enums-in-typescript-1c1j
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To