Open In App

How to Iterate over Enum Values in TypeScript?

Last Updated : 09 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Enums in TypeScript are a way to define a set of named constants. Sometimes we may need to iterate over all the values of an enum. There are several approaches to iterate over the enum values in TypeScript which are as follows:

Examples of Iterating over Enum Values in TypeScript

Using a for…in loop

In this approach, we are using a for…in loop to iterate over the keys of the enum and access the corresponding values. It is important to check if the property is a key of the enum to avoid iterating over any prototype properties.

Syntax:

for (const key in Enum) {
// Use 'value' as needed
}

Example: The below code uses for…in loop to iterate over enum values in typescript

JavaScript
enum StudentInfo {
    Name = "Yogesh",
    RollNo = "14",
    Branch = "Civil",
    Div = "A",
}

for (const key in StudentInfo) {
    if (StudentInfo.hasOwnProperty(key)) {
        console.log(StudentInfo[key]);
    }
}

Output:

Yogesh
14
Civil
A

Using Object.values()

In this approach, we will be using the Object.values() method. This method is used to extract the values of the enum. It returns an array containing the enum values, which can then be iterated over using array methods or loops.

Syntax:

const values = Object.values(YourEnum);
values.forEach(value => {
// Use 'value' as needed
});

Example: This example uses Object.values() to iterate over enum values in typescript.

JavaScript
enum GFG {
    Name = "GeeksForGeeks",
    Founder = "Sandeep Jain",
    Est = "2008"
}

const values = Object
    .values(GFG);
values
    .forEach(value => console.log(value));

Output:

GeeksForGeeks
Sandeep Jain
2008

Using a for…of loop

The for…of loop offers a streamlined approach to directly iterate over the values of an enum without the need for additional property checks. This loop provides a concise syntax for traversing enum values, enhancing code readability and maintainability.

Syntax:

for (const value of YourEnum) {
// Use 'value' as needed
}

Example:

JavaScript
enum Direction {
  North = "N",
  South = "S",
  East = "E",
  West = "W",
}

for (const value of Object.values(Direction)) {
  console.log(value);
}

Output:

N
S
E
W

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads