Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over enums TypeScript

I'm trying to iterate over this enum. However I'm facing issues with extracting values from the enum. I can extract the value if i give it a hardcoded string like this.

export enum Values {
  ACE = 'A',
  TWO = '2',
  THREE = '3',
  FOUR = '4',
  FIVE = '5',
  SIX = '6',
  SEVEN = '7',
  EIGHT = '8',
  NINE = '9',
  TEN = '10',
  JACK = 'J',
  QUEEN = 'Q',
  KING = 'K',
}

console.log(Values['TWO']);


But as soon as i give it the multiple string values from the enum like below.

export enum Values {
  ACE = 'A',
  TWO = '2',
  THREE = '3',
  FOUR = '4',
  FIVE = '5',
  SIX = '6',
  SEVEN = '7',
  EIGHT = '8',
  NINE = '9',
  TEN = '10',
  JACK = 'J',
  QUEEN = 'Q',
  KING = 'K',
}

for (let value in Values) {
  console.log(Values[value]);
}

It gives the following error:

error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof Values'.
  No index signature with a parameter of type 'string' was found on type 'typeof Values'.

25   console.log(Values[value]);

Completely new to TypeScript so might be missing something.

Cheers to anyone who could give me some guidance.

like image 425
ToxicTuring Avatar asked Oct 28 '25 14:10

ToxicTuring


1 Answers

The type of the loop variable while iterating using for-in loop over enum Values is implicitly any, so you get the compile error.

for (let value in Values) {
  console.log(Values[value]);
}

The variable value is of type any, which cannot be used to index the enum Values.

Open issue in TypeScript here.

If you want to iterate over the key-value pairs of the enum you can do so with the help of Object.entries:

enum Values {
  ACE = 'A',
  TWO = '2',
  THREE = '3',
  FOUR = '4',
  FIVE = '5',
  SIX = '6',
  SEVEN = '7',
  EIGHT = '8',
  NINE = '9',
  TEN = '10',
  JACK = 'J',
  QUEEN = 'Q',
  KING = 'K',
}

//Both key and value
Object.entries(Values).forEach(([key, value]) => {
    console.log(key, value)
});

//keys
Object.keys(Values).forEach(key => {
    console.log(key);
});

//values
Object.values(Values).forEach(value => {
    console.log(value);
});
like image 187
Fullstack Guy Avatar answered Oct 31 '25 05:10

Fullstack Guy