Course contentsShow
← TypeScript
Lesson 521 of 1,79612. EnumsFree lesson

Iteration and Reflection Trade-offs

Enums allow runtime iteration over values; unions require manual arrays for the same capability.

Iteration and Reflection Trade-offs

What you'll learn: How enums and union types differ when you need to loop over possible values or inspect them at runtime.

The Runtime vs Compile-Time Divide

Here's a crucial difference between enums and string-literal unions: enums exist at runtime, while unions are purely compile-time constructs.

This means if you declare an enum, you can iterate over its members in your running JavaScript code. With a union type, the type information disappears after compilation — you can't loop over "all possible values" without manually creating an array yourself.

Enums: Built-In Iteration

Because enums compile to real JavaScript objects, you can treat them like objects:

enum Status {
  Pending = "PENDING",
  Active = "ACTIVE",
  Completed = "COMPLETED"
}

// You can iterate over enum values at runtime
Object.values(Status).forEach(status => {
  console.log(status); // PENDING, ACTIVE, COMPLETED
});

The enum itself is a real object in your running code.

Unions: Manual Array Required

With a string-literal union, you get type safety but no runtime object:

type Status = "PENDING" | "ACTIVE" | "COMPLETED";

// The type exists only at compile-time
// To iterate, you must manually maintain an array:
const statusValues = ["PENDING", "ACTIVE", "COMPLETED"] as const;

statusValues.forEach(status => {
  console.log(status);
});

You have to keep the array and the type in sync manually.

The Trade-off

Enums give you reflection and iteration for free but add runtime code. Unions keep your bundle smaller but require manual work when you need to loop over values or check membership dynamically.

Key Takeaway: Enums provide runtime iteration capabilities automatically; unions require you to manually create and maintain arrays of values if you need the same functionality.