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 FruitVa…


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


Print Share Comment Cite Upload Translate Updates
APA

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/

MLA
" » Mastering Enums in TypeScript." Arnaud Leymet | Sciencx - Tuesday July 27, 2021, https://www.scien.cx/2021/07/27/mastering-enums-in-typescript/
HARVARD
Arnaud Leymet | Sciencx Tuesday July 27, 2021 » Mastering Enums in TypeScript., viewed ,<https://www.scien.cx/2021/07/27/mastering-enums-in-typescript/>
VANCOUVER
Arnaud Leymet | Sciencx - » Mastering Enums in TypeScript. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/07/27/mastering-enums-in-typescript/
CHICAGO
" » Mastering Enums in TypeScript." Arnaud Leymet | Sciencx - Accessed . 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: ]
rf:citation
» Mastering Enums in TypeScript | Arnaud Leymet | Sciencx | 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.

You must be logged in to translate posts. Please log in or register.