Iterating over enum keys in TypeScript

 Let us look at this simple enum:

export enum MyEnum {
    Key1 = 1,
    Key2 = 2
}

We cannot simply use this syntax:

MyEnum["Something"]

Since it does not expect a string but rather a special type which is a union of all the key names.

let key: keyof MyEnum

then we can iterate over it like this:

for (key in MyEnum) {
    console.log(MyEnum[key]);
}

Post a Comment

Previous Post Next Post