2

I noticed this just now when trying to iterate over an enum.

Say you have:

enum Gender {
    Male = 1,
    Female = 2
}

and you do:

for (let gender in Gender) {
    console.log(gender)
}

This will run 4 (?) times. First printing string (!) representations of 1 and 2, then printing the strings Male and Female.

I can only suppose this is intended. My question is why this is the case? What's the reasoning behind this (in my opinion) weird implementation?

1 Answer 1

8

JS has no enum. TS compiles your enum to:

var Gender;
(function (Gender) {
    Gender[Gender["Male"] = 1] = "Male";
    Gender[Gender["Female"] = 2] = "Female";
})(Gender || (Gender = {}));

Where you can see has 4 keys (1,2,Male,Female).

You can use this site for checking the TS to JS compilation output.

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

2 Comments

That makes sense. But what does the for loop compile to then? Wouldn't it make sense to also compile the loop to reflect the TS enum, and not the underlying JS?
The for...in statement iterates over all non-Symbol, enumerable properties of an object. - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

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.