How to Iterate Enums in TypeScript

In TypeScript, 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.

Numeric Enums

By default, TypeScript enums are numeric. Let's consider the following Color enum:

enum Color { Red, Green, Blue }

Iterating Over Enum Values

You can iterate over the numeric enum values using a simple for loop:

for (let colorValue = 0; colorValue < Object.keys(Color).length / 2; colorValue++) { console.log(colorValue); // 0, 1, 2 }

Iterating Over Enum Names

To iterate over the names of the enum members:

for (let colorName of Object.keys(Color).slice(0, Object.keys(Color).length / 2)) { console.log(colorName); // "Red", "Green", "Blue" }

String Enums

String enums are a feature introduced in TypeScript 2.4 which allow you to associate string values with the name of enum members.

enum Shape { Circle = "CIRCLE", Square = "SQUARE", Triangle = "TRIANGLE" }

Iterating Over String Enum Values

For string enums, you can iterate over the values using the Object.values() function:

for (let shapeValue of Object.values(Shape)) { console.log(shapeValue); // "CIRCLE", "SQUARE", "TRIANGLE" }

Iterating Over String Enum Names

To iterate over the names of the string enum members:

for (let shapeName of Object.keys(Shape)) { console.log(shapeName); // "Circle", "Square", "Triangle" }

Heterogeneous Enums

Enums can mix string and numeric members:

enum MixedEnum { First = 1, Second = "SECOND", Third }

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:

for (let key in MixedEnum) { if (typeof MixedEnum[key] === 'number') { console.log(MixedEnum[key]); // Logs the numeric values } else { console.log(MixedEnum[key]); // Logs the string values } }

Caveats

  1. Ambiguity in Object Methods: Using Object.keys() or Object.values() on a numeric enum returns both the names and values because numeric enums are reverse-mapped. Hence the slicing we did earlier.
  2. 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.

Invite only

We're building the next generation of data visualization.