1

Consider the code below. I assumed that i could loop through an enum and pass an instance of it to a function that takes the enum as parameter.

However, it seems that let color in Colors produced color of type string instead of type Colors. Am I missing a cast somewhere? Why doesn't enum loop produce a value of said Enum?

enum Colors {
    Red = "Red",
    Green = "Green",
    Yellow = "Yellow"
}

for (let color in Colors) {
  doStuff(color);
}

function doStuff(mycolor: Colors) {
  console.log(mycolor)
}

1 Answer 1

3

Use Object.values as for loop just treats it as iterating over an object

enum Colors {
  Red = "Red",
  Green = "Green",
  Yellow = "Yellow"
}

function doStuff(mycolor: Colors): void {
  console.log(mycolor);
}

Object.values(Colors).forEach(color => doStuff(color));

I guess Colours are only the values and not the enum entries, as you can use this too:

Object.entries(Colors).forEach((color: [string, Colors]) => doStuff(color[1]));

Also bear in mind that for loops generally are not good for things that don't have if or switch statement. Interestingly if you do add deeper logic to the for loop, TypeScript does determine the type:

for (const color in Colors) {
  if (color === Colors.Green) { 
    // Now the cat is either dead or alive 
    doStuff(color);
  }
}

Object.entries is still new so ensure that your tsconfig.json is referencing es2017 as an entry for compilerOptions/lib.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for reminding me. I will edit the answer to include this
To really get the value of TS enable compilerOptions/strict: true as well.
Well, that opened a can of worms.
Excellent. I'd like to add one small thing. in tsconfig.json, it's necessary to add es2017 to compilerOptions/lib entry.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.