Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 27, 2021 04:06 pm GMT

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:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To