TypeScript example

How to loop through an enum in TypeScript

8 min read Updated Nov 2026 Runs in an isolated runtime
Quick answer

An enum is a plain object at runtime, so loop over Object.values(Direction) for the values and Object.keys(Direction) for the names. For a string enum that is all you need. A numeric enum also maps every value back to its name, so filter that half out: Object.keys(Color).filter((key) => Number.isNaN(Number(key))) gives [ 'Red', 'Green', 'Blue' ].

TypeScript has no built-in way to list an enum's members, and it doesn't need one: unlike most types, a regular enum compiles to a real JavaScript object, with one property per member. Object.keys, Object.values and Object.entries read it like any other object. What TypeScript adds is the typing of those results, and one trap: numeric enums carry a reverse mapping that doubles every key. The sections below cover string enums, numeric enums, turning an enum into an array of options for a dropdown, reusable typed helpers, and why a const enum can't be looped at all. Each example runs on this page: hit Run, then edit the code and run it again.

1String enums: Object.values and Object.keysRecommended

A string enum compiles to an object whose keys are the member names and whose values are the strings you gave them, so Object.values returns the values and Object.keys the names, both in declaration order. The two calls aren't typed alike. Object.values(Direction) is typed Direction[], so each item can go straight into a function that takes a Direction. Object.keys always returns string[], whatever the object, so to read Direction[name] you cast the array once to (keyof typeof Direction)[], the union of the member names.

string-enum.ts
enum Direction {
    Up = "UP",
    Down = "DOWN",
    Left = "LEFT",
    Right = "RIGHT",
}

// A string enum compiles to a plain object: { Up: "UP", Down: "DOWN", ... }
const values: Direction[] = Object.values(Direction);
const names = Object.keys(Direction); // string[]

console.log(values);
console.log(names);

// Both lists come back in declaration order
for (const direction of Object.values(Direction)) {
    console.log(`move ${direction}`);
}

// Object.keys gives plain strings: cast once to index the enum
for (const name of Object.keys(Direction) as (keyof typeof Direction)[]) {
    console.log(`${name} = ${Direction[name]}`);
}

Output

The values print as [ 'UP', 'DOWN', 'LEFT', 'RIGHT' ] and the names as [ 'Up', 'Down', 'Left', 'Right' ]. Without the cast, Direction[name] with a string name runs fine on this page, whose compiler has strict off, but with strict on, as in most projects, it fails with error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof Direction'. The cast is safe here because the keys of a string enum are exactly its names. The same loop works in plain JavaScript on any object; see loop through an object for why Object.keys isn't typed keyof.

2Numeric enums: filter out the reverse mapping

A numeric enum is where the top Stack Overflow question comes from. TypeScript compiles it to an object that maps both ways, names to numbers and numbers back to names, so that Color[0] is "Red". Every member therefore appears twice in Object.keys and Object.values. To get the names, keep the keys that don't parse as a number. To get the values, keep the items that are numbers, and use a type guard (value is Color) so the result is typed Color[] instead of (string | Color)[].

numeric-enum.ts
enum Color {
    Red,
    Green,
    Blue,
}

// A numeric enum also maps each value back to its name: Color[0] === "Red"
console.log(Object.keys(Color));
console.log(Object.values(Color));

// Names: keep the keys that are not numbers
const names = Object.keys(Color).filter((key) => Number.isNaN(Number(key)));

// Values: keep the numbers; the type guard makes the result Color[]
const values = Object.values(Color).filter(
    (value): value is Color => typeof value === "number",
);

console.log(names);
console.log(values);

// The reverse mapping turns a value back into its name
for (const value of values) {
    console.log(`${value} -> ${Color[value]}`);
}

Output

The raw keys are [ '0', '1', '2', 'Red', 'Green', 'Blue' ]: the reverse-mapping keys come first, because JavaScript lists integer-like keys before the others. After the filters you get [ 'Red', 'Green', 'Blue' ] and [ 0, 1, 2 ], and Color[value] turns each value back into its name (1 -> Green). A for...in loop visits the same six keys as Object.keys, so it needs the same filter. Without the type guard, Object.values(Color) is typed (string | Color)[], and assigning it to a Color[] fails even on this page with error TS2322: Type '(string | Color)[]' is not assignable to type 'Color[]'.

3Turn an enum into an array of options

For radio buttons, a <select> or an API response you usually want one object per member, holding the name to show and the value to store. Object.entries gives [name, value] pairs; filter out the reverse-mapping pairs and map the rest. The type guard on the filter, entry is [string, Plan], is what lets the map build a PlanOption whose value is a Plan and not a string | Plan.

enum-to-options.ts
enum Plan {
    Free,
    Pro,
    Team,
}

interface PlanOption {
    label: string;
    value: Plan;
}

// One entry per member: [name, value] pairs, minus the reverse mapping
const options: PlanOption[] = Object.entries(Plan)
    .filter((entry): entry is [string, Plan] => typeof entry[1] === "number")
    .map(([label, value]) => ({ label, value }));

console.log(options);

// e.g. radio buttons or a <select>: the value stays a Plan
const selected = Plan.Pro;
for (const { label, value } of options) {
    const mark = value === selected ? "(x)" : "( )";
    console.log(`${mark} ${label}`);
}

Output

The array prints as { label: 'Free', value: 0 }, { label: 'Pro', value: 1 } and { label: 'Team', value: 2 }, and because each value is still a Plan, comparing it with Plan.Pro needs no cast. For a string enum, drop the filter: Object.entries(Direction) already has one pair per member. For labels other than the member names, such as "Pro plan", keep a Record<Plan, string> next to the enum and look the label up in the map; the Record type makes the checker insist on a label for every member.

4Typed helpers for any enum

With several enums, write the filter once. A parameter typed E extends Record<string, string | number> accepts any enum object, string or numeric, and Extract<keyof E, string> is the union of its member names (it drops the number keys of the reverse mapping). enumNames filters the keys as in section 2, and enumValues reads each value through its name. Going through the names, rather than keeping the numbers from Object.values, is what makes the helper work on enums that mix numbers and strings.

enum-helpers.ts
// Any enum object: names map to numbers or strings
type EnumObject = Record<string, string | number>;
type EnumName<E extends EnumObject> = Extract<keyof E, string>;

// Names are the keys that are not numbers (drops the reverse mapping)
function enumNames<E extends EnumObject>(e: E): EnumName<E>[] {
    return Object.keys(e).filter((key) => Number.isNaN(Number(key))) as EnumName<E>[];
}

// Values come from the names, so string members of mixed enums survive
function enumValues<E extends EnumObject>(e: E): E[EnumName<E>][] {
    return enumNames(e).map((name) => e[name]);
}

enum Size {
    Small = "S",
    Large = "L",
}

enum Level {
    Low = 1,
    High = 10,
    Max = -1,
}

enum Answer {
    No = 0,
    Yes = "YES",
}

const sizes: Size[] = enumValues(Size);
const levels: Level[] = enumValues(Level);

console.log(enumNames(Size), sizes);
console.log(enumNames(Level), levels);
console.log(enumNames(Answer), enumValues(Answer));

Output

enumValues(Size) is typed Size[] and enumValues(Level) Level[], so both assignments compile without a cast. Level shows that the names keep declaration order and that a negative value is no problem: [ 1, 10, -1 ]. The mixed Answer enum gives [ 0, 'YES' ]; filtering Object.values by typeof value === "number" would have lost 'YES'. The one cast, as EnumName<E>[], sits inside the helper, so callers never write one.

5A const enum cannot be looped

A const enum exists only at compile time: every Weekday.Tue is replaced by its value, "TUE", and no object is emitted. There is nothing for Object.values to read, so the checker rejects any use of the enum that isn't a member access. This embed fails on purpose: the type error stops the run before anything executes, including the first console.log.

const-enum.ts
// A const enum is inlined at compile time: no object exists at runtime
const enum Weekday {
    Mon = "MON",
    Tue = "TUE",
    Wed = "WED",
}

const today = Weekday.Tue; // fine: compiles to "TUE"
console.log(today);

// Nothing to loop over, so the checker rejects it
for (const day of Object.values(Weekday)) {
    console.log(day);
}

Output

The compiler reports error TS2475: 'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query. If you need to loop over the members, remove const and the code above works as in section 1. The other common choice is an as const object, which is real runtime data that Object.values can read and from which you derive the union of its values as a type; see create a union type from an array.

6Which should you use?

For a string enum, Object.values and Object.keys are all you need. For a numeric enum, filter, and give the filter a type guard when you want typed values. Reach for the helpers once more than one enum needs listing, or when an enum mixes numbers and strings.

MethodResult typeNumeric enumsBest for
Object.values(E)E[] for a string enumNames mixed inValues of a string enum
Object.keys(E) as (keyof typeof E)[]Member namesNumber keys mixed inNames of a string enum
Object.keys(E).filter(isNaN)string[]WorksNames of a numeric enum
Object.values(E).filter(guard)E[]WorksValues of a numeric enum
Object.entries + filter + mapYour option typeWorksDropdowns, radio buttons, APIs
enumNames / enumValuesNames union / E[]Works, mixed enums tooMany enums in one codebase

Frequently asked questions

Why does Object.keys on my enum return numbers?

Because it is a numeric enum. TypeScript compiles enum Color { Red, Green, Blue } to an object with a reverse mapping, so it has the keys 0, 1, 2 (pointing at the names) as well as Red, Green, Blue (pointing at the numbers): Object.keys(Color) gives [ '0', '1', '2', 'Red', 'Green', 'Blue' ]. Filter with Number.isNaN(Number(key)) to keep the names. String enums have no reverse mapping, so their keys are just the names.

How do I get the name of an enum value?

For a numeric enum, index the enum with the value: Color[Color.Green] is Green, thanks to the reverse mapping. A string enum has no reverse mapping (indexing it with "DOWN" gives undefined), so search the keys: Object.keys(Direction).find((key) => Direction[key as keyof typeof Direction] === Direction.Down) returns Down.

How do I count the members of an enum?

Count the names, not the keys. For a string enum Object.keys(Direction).length is right, but for a numeric enum it counts every member twice: three members give 6. Use Object.keys(Color).filter((key) => Number.isNaN(Number(key))).length. Halving the key count only works when no two members share a value.

What happens when two enum members have the same value?

Both names are kept, but the reverse mapping holds only the last one. With enum Priority { High = 10, Low = 1, None = -1, Default = 1 }, the name filter returns [ 'High', 'Low', 'None', 'Default' ] and the number filter [ 10, 1, -1, 1 ], with the duplicate, while Priority[1] is Default, not Low. Loop over the names when every member matters.

Can I loop over a union type like "a" | "b" | "c"?

No. A union type is erased when the code compiles, so there is nothing to loop over at runtime. Turn it around: write the values once as an array as const, loop over the array, and derive the union type from it with (typeof values)[number]. The create-a-union-type-from-an-array example covers this.

Does the order of Object.values match the enum declaration?

For the names, yes: string keys come back in the order they were defined, so the filters return members in declaration order. The reverse-mapping keys of a numeric enum are integer-like, and JavaScript lists those first in ascending order, which is why the raw Object.keys(Priority) for the enum in the duplicate-values answer above is [ '1', '10', 'High', 'Low', 'None', '-1', 'Default' ], starting with '1' and '10'. A negative value such as -1 is not an integer index, so its key '-1' stays in definition order. The filters remove these keys either way.

Run it yourself

Open any of these in the full TypeScript editor to tweak, run and share.

TypeScript playground