-1

I have an enum in typscript:

export enum MyEnum{
    value1,
    value2
}

And I have an array of enums:

let myEnumValues: Array<string | number> = [];

And I push an enum in:

myEnumValues.push(MyEnum.value2)

And if print the array:

console.log(myEnumValues);
// [ 1 ]

And if I loop through the array and print that:

for (var myEnumValue in myEnumValues) {
   console.log(myEnumValue);
   // 0
}

Why is it that I loop through an array that contains one item 1 and when I print it it's 0? I tried many variations and it is always different.

I can't figure it out.

Nick
  • 2,877
  • 2
  • 33
  • 62

2 Answers2

0

The answer is:

for (var myEnumValue of myEnumValues) {

instead of

for (var myEnumValue in myEnumValues) {

Nick
  • 2,877
  • 2
  • 33
  • 62
-1

By default when using enum in TypeScript, it's a numeric enum, meaning: The value for each key is a number that corresponds with the index of the key.

If you want string values, you'll have to define a string value per key:

export enum MyEnum{
    value1 = 'value1',
    value2 = 'value2'
}
fjc
  • 5,590
  • 17
  • 36