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
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
Contact Us