How to Iterate Enums in TypeScript
October 26, 2023
enum is a way of giving more friendly names to sets of numeric or string values. Often, developers want to iterate over the members of an enum. In this guide, we'll look at multiple ways of iterating over enums in TypeScript.
By default, TypeScript enums are numeric. Let's consider the following
Iterating Over Enum Values
You can iterate over the numeric enum values using a simple for loop:
Iterating Over Enum Names
To iterate over the names of the enum members:
String enums are a feature introduced in TypeScript 2.4 which allow you to associate string values with the name of enum members.
Iterating Over String Enum Values
For string enums, you can iterate over the values using the
Iterating Over String Enum Names
To iterate over the names of the string enum members:
Enums can mix string and numeric members:
For heterogeneous enums, you might need to employ more specific logic based on the type of each member, using type guards.
Iterating Over Heterogeneous Enum Values
You can iterate over the values and apply type-specific logic:
- Ambiguity in Object Methods: Using
Object.values()on a numeric enum returns both the names and values because numeric enums are reverse-mapped. Hence the slicing we did earlier.
- Order: The order of iteration is based on how the members are defined in the enum. If the enum order changes, the iteration order will change accordingly.
Remember, enums in TypeScript can be powerful tools. While iteration over them is straightforward, understanding the underlying structure is crucial to avoid unexpected behaviors.
How to fix the "not all code paths return a value" issue in TypeScript
Working with WebSockets in Node.js using TypeScript
Type Annotations Can Only Be Used in TypeScript Files
Guide to TypeScript Recursive Type
How to Configure Knex.js with TypeScript