loop through enum in typescript

In TypeScript, you can loop through an enum by using the for...in loop. Here's an example:

index.ts
enum Color {
  Red,
  Green,
  Blue
}

for (let color in Color) {
  console.log(color); // Outputs "Red", "Green", "Blue"
}
124 chars
10 lines

Note that the for...in loop also iterates over any properties added to the enum object (e.g. Color["0"] === "Red"). To avoid this, you can use a type guard to check if the property is a number:

index.ts
enum Color {
  Red,
  Green,
  Blue
}

for (let key in Color) {
  if (typeof Color[key] === "number") {
    console.log(key); // Outputs "Red", "Green", "Blue"
  }
}
166 chars
12 lines

Alternatively, you can loop through the values of an enum using the Object.values() method:

index.ts
enum Color {
  Red,
  Green,
  Blue
}

const colors = Object.values(Color) as string[];
for (let color of colors) {
  console.log(color); // Outputs "Red", "Green", "Blue"
}
174 chars
11 lines

related categories

gistlibby LogSnag