Iterate over enum items in Typescript

Viewed 6171

How do I iterate over enum items in TypeScript? I tried for-in, but this iterates over strings. I need to call a function for each enum value.

for (const foo in FooType) {
    // here I have error that string is not assignable to parameter of type FooType
    this.doCalculation(foo)
}


private doCalculation(value: FooType): void {
   // some logic
}

enum FooType looks like this:

export enum SupportedFiat {
  VALUE_A = 'VALUE_A',
  VALUE_B = 'VALUE_B',
  VALUE_C = 'VALUE_C'
}
2 Answers

You should be able to accomplish this using for of and Object.values.

for (const value of Object.values(FooType)) {
  // here I have error that string is not assignable to parameter of type FooType
  doCalculation(value)
}

enums are translated to this type of object:

"use strict";
var SupportedFiat;
(function (SupportedFiat) {
    SupportedFiat["VALUE_A"] = "VALUE_A";
    SupportedFiat["VALUE_B"] = "VALUE_B";
    SupportedFiat["VALUE_C"] = "VALUE_C";
})(SupportedFiat || (SupportedFiat = {}));

Playground link

unfortunately, Typescript enums don't really implement an iterator for easy iterating so you need to make your own:

function* supportedFiatValues(): IterableIterator<SupportedFiat> {
    yield SupportedFiat.VALUE_A;
    yield SupportedFiat.VALUE_B;
    yield SupportedFiat.VALUE_C;
}

for (const supportedFiat of supportedFiatValues()) {
// ...
}

You could use Object.values() but you'll lose type information there, IMHO the generator approach brings you better type inference.

Related