Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through TypeScript enum?

Tags:

typescript

I have next enum:

export enum Suite {
  Spade = '♠',
  Heart = '♥',
  Club = '♣',
  Diamond = '♦',
}

Trying to implement loop, but getting error

  for (let suite in Suite) {
    console.log('item:', Suite[suite]);
  }

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof Suite'. No index signature with a parameter of type 'string' was found on type 'typeof Suite'.ts(7053)

Screenshot

How can I fix that?

like image 430
acidernt Avatar asked Mar 08 '26 07:03

acidernt


1 Answers

You need to narrow the type of your suite key with a type constraint. You can do this by declaring it before the loop:

enum Suite {
  Spade = '♠',
  Heart = '♥',
  Club = '♣',
  Diamond = '♦',
}

let suite: keyof typeof Suite;
for (suite in Suite) {
    const value = Suite[suite];
    // ...
}

Or use Object.entries:

for (const [key, value] of Object.entries(Suite)) {
    // key = Spade, etc.
    // value = ♠, etc.
}

Playground

like image 59
Connor Low Avatar answered Mar 09 '26 20:03

Connor Low



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!