Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over enum items in Typescript

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'
}
like image 306
Denis Stephanov Avatar asked May 17 '26 11:05

Denis Stephanov


1 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)
}
like image 171
Mark Skelton Avatar answered May 19 '26 04:05

Mark Skelton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!