Skip to content
typescript

Typescript: how to iterate over enum values?

Jul 23, 2023Abhishek EH1 Min Read
Typescript: how to iterate over enum values?

Consider the following enum:

1enum Color {
2 Red = "R",
3 Green = "G",
4 Blue = "B",
5}

If you want to loop through the keys of the enum, first retrieve the keys using Object.keys and then loop through the keys:

1Object.keys(Color).forEach(key => {
2 console.log(key) // Red, Green, Blue
3})

To loop through the values of the enum, use Object.values:

1Object.values(Color).forEach(value => {
2 console.log(value) // R, G, B
3})

When we do not specify the values of the enum, the values are automatically assigned to the keys. In this case, we can loop through the enum values using Object.keys and filter out the strings which are not numbers:

1enum Color {
2 Red,
3 Green,
4 Blue,
5}
6
7Object.keys(Color)
8 .filter(key => isNaN(Number(key)))
9 .forEach(key => {
10 console.log(key) // Red, Green, Blue
11 })

To loop through the enum values, we can use Object.values and filter out the values which are numbers:

1Object.values(Color)
2 .filter(value => typeof value === "number")
3 .forEach(value => {
4 console.log(value) // 0, 1, 2
5 })

Do follow me on twitter where I post developer insights more often!

Leave a Comment

© 2023 CodingDeft.Com