How to use a for…in loop In Typescript

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

How to Iterate over Enum Values in TypeScript?

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:

Table of Content

  • Using a for…in loop
  • Using Object.values()
  • Using a for…of loop

Similar Reads

Examples of Iterating over Enum Values in TypeScript

Using a for…in loop...

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....

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....

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....