How to Iterate Over Enums in TypeScript?

As a TypeScript developer, I frequently encounter scenarios where I need to loop through an enum to access its keys or values. In this complete tutorial, I’ll show you multiple methods to iterate over TypeScript enums, with practical examples and best practices that I’ve developed through years of TypeScript development.

Enums (enumerations) provide a way to define named constants in TypeScript, making our code more readable and maintainable, but working with them isn’t always intuitive.

What Are TypeScript Enums?

Before checking out various iteration techniques, let’s quickly review what enums are in TypeScript:

enum Fruits {
  Apple = "apple",
  Banana = "banana",
  Orange = "orange"
}

Enums allow us to define a set of named constants, making our code more readable and helping us avoid the dreaded “magic strings” problem.

Method 1: Using Object.keys() to Iterate Over Enum Keys

The simplest way to iterate over an enum in TypeScript is to leverage JavaScript’s built-in Object.keys() method:

enum Direction {
  North = "NORTH",
  South = "SOUTH",
  East = "EAST",
  West = "WEST"
}

// Get all the keys (North, South, East, West)
const keys = Object.keys(Direction);

// Loop through the keys
keys.forEach(key => {
  console.log(key);
});

Here is the exact output in the screenshot below:

Iterate Over Enums in TypeScript

However, there’s a catch: numeric enums in TypeScript create reverse mappings, which means Object.keys() would include both the keys and the values. To handle this properly:

enum NumericDirection {
  North = 0,
  South = 1,
  East = 2,
  West = 3
}

// This filters out numeric values
const keys = Object.keys(NumericDirection).filter(key => isNaN(Number(key)));

keys.forEach(key => {
  console.log(key); // North, South, East, West
});

Check out Convert String to Enum in Typescript

Method 2: Using Object.values() to Iterate Over Enum Values

If you need to iterate over the values rather than keys, you can use Object.values() in TypeScript:

enum Fruits {
  Apple = "apple",
  Banana = "banana",
  Orange = "orange"
}

const values = Object.values(Fruits);

values.forEach(value => {
  console.log(value); // "apple", "banana", "orange"
});

This works well for string enums, but for numeric enums, you’ll need similar filtering:

enum Status {
  Active = 1,
  Inactive = 2,
  Pending = 3
}

// Only get the values
const values = Object.values(Status).filter(value => !isNaN(Number(value)));

values.forEach(value => {
  console.log(value); // 1, 2, 3
});

Check out TypeScript Enum Reverse Mapping

Method 3: Using for…in Loop for TypeScript Enum Iteration

Another approach to loop through enum in TypeScript is to use a traditional for...in loop, which can be useful in certain scenarios:

enum CarBrands {
  Toyota = "TOYOTA",
  Ford = "FORD",
  Tesla = "TESLA"
}

for (const key in CarBrands) {
  // Check if the property is a key (not a reverse mapping)
  if (isNaN(Number(key))) {
    console.log(key); // Key: Toyota, Ford, Tesla
    console.log(CarBrands[key]); // Value: "TOYOTA", "FORD", "TESLA"
  }
}

This method gives you access to both keys and values simultaneously, which can be convenient for certain operations.

After I executed the PowerShell script using VS code, you can see the exact output in the screenshot below:

typescript iterate over enum

Read How to Get Key by Value from enum String in Typescript

Method 4: Converting Enums to Array of Key-Value Pairs

When I need to work with both keys and values together, I often convert the enum to an array of key-value pairs:

enum States {
  California = "CA",
  Texas = "TX",
  Florida = "FL",
  NewYork = "NY"
}

const stateEntries = Object.entries(States).filter(([key]) => isNaN(Number(key)));

stateEntries.forEach(([key, value]) => {
  console.log(`${key}: ${value}`); // California: CA, Texas: TX, etc.
});

This approach is particularly useful when you need to display enum data in UI components like dropdown menus.

Method 5: Using for…of Loop with Object.keys()

The for…of loop offers a more streamlined approach to iterate over enum values in TypeScript:

enum Seasons {
  Spring = "SPRING",
  Summer = "SUMMER",
  Fall = "FALL",
  Winter = "WINTER"
}

for (const season of Object.keys(Seasons)) {
  if (isNaN(Number(season))) {
    console.log(season); // Spring, Summer, Fall, Winter
  }
}

You can see the exact output in the screenshot below:

typescript loop through enum

Method 6: Create Utility Functions for Enum Iteration

To make enum iteration more reusable across your codebase, I recommend creating utility functions:

// Utility function to get enum keys
function getEnumKeys<T extends object>(enumObj: T): (keyof T)[] {
  return Object.keys(enumObj).filter(key => isNaN(Number(key))) as (keyof T)[];
}

// Utility function to get enum values
function getEnumValues<T extends object>(enumObj: T): T[keyof T][] {
  return getEnumKeys(enumObj).map(key => enumObj[key]);
}

// Usage example
enum PaymentMethod {
  CreditCard = "CREDIT_CARD",
  DebitCard = "DEBIT_CARD",
  PayPal = "PAYPAL",
  ApplePay = "APPLE_PAY"
}

const keys = getEnumKeys(PaymentMethod);
console.log(keys); // ["CreditCard", "DebitCard", "PayPal", "ApplePay"]

const values = getEnumValues(PaymentMethod);
console.log(values); // ["CREDIT_CARD", "DEBIT_CARD", "PAYPAL", "APPLE_PAY"]

These utility functions can be exported and reused throughout your project, making your code more DRY and maintainable.

Check out TypeScript Promise

Advanced Techniques: Working with Complex Enums

Sometimes, you’ll need to iterate over complex enum structures. Here’s how to handle those scenarios:

Iterate Over Computed Enum Values

Here is the TypeScript code to iterate over enum in TypeScript (Complex).

enum ApiEndpoints {
  Users = `${API_BASE_URL}/users`,
  Products = `${API_BASE_URL}/products`,
  Orders = `${API_BASE_URL}/orders`
}

// The same methods work for computed values too
const endpoints = Object.values(ApiEndpoints);
endpoints.forEach(endpoint => {
  console.log(`Fetching data from: ${endpoint}`);
});

Working with Heterogeneous Enums

When dealing with enums that have mixed types (string and numeric values):

enum MixedEnum {
  A = 0,
  B = "B",
  C = 2,
  D = "D"
}

// Get string values
const stringValues = Object.values(MixedEnum).filter(val => typeof val === "string");
// Get numeric values
const numericValues = Object.values(MixedEnum).filter(val => typeof val === "number");

console.log(stringValues); // ["B", "D"]
console.log(numericValues); // [0, 2]

Performance Considerations

When typescript loop through enum operations are executed in performance-critical code, it’s worth noting some differences between methods:

MethodPerformanceMemory UsageUse Case
Object.keys()FastLowWhen you need only keys
Object.values()FastLowWhen you need only values
for…in loopModerateVery LowWhen you need both keys and values
Object.entries()SlowerHigherWhen you need structured key-value pairs

For most applications, the performance differences are negligible, but in high-frequency operations, the for…in loop might offer slight advantages.

Real-World Example: Building a Dropdown Component

Now, let me show you a practical example where we are trying to iterate over enum in TypeScript.

Here’s a practical example of how I use enum iteration in React to build a dropdown component:

enum USStates {
  Alabama = "AL",
  Alaska = "AK",
  Arizona = "AZ",
  // ... more states
}

function StateDropdown({ onChange }: { onChange: (state: USStates) => void }) {
  return (
    <select onChange={(e) => onChange(e.target.value as USStates)}>
      {Object.entries(USStates)
        .filter(([key]) => isNaN(Number(key)))
        .map(([stateName, stateCode]) => (
          <option key={stateCode} value={stateCode}>
            {stateName}
          </option>
        ))}
    </select>
  );
}

Conclusion

In this tutorial, I have explained different methods to loop through enums in TypeScript. Here is a summary of each technique and which one to use when.

  • Use Object.keys() and Object.values() for simple key/value iteration
  • Use for...in loops when you need both keys and values simultaneously
  • Create utility functions for reusable, type-safe operations
  • Be mindful of reverse mappings in numeric enums

Do let me know if you have any issues in the comment below.

Power Apps functions free pdf

30 Power Apps Functions

This free guide walks you through the 30 most-used Power Apps functions with real business examples, exact syntax, and results you can see.

Download User registration canvas app

DOWNLOAD USER REGISTRATION POWER APPS CANVAS APP

Download a fully functional Power Apps Canvas App (with Power Automate): User Registration App