Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript - weird behaviour when iterating over an enum

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?

like image 547
Viggo Lundén Avatar asked Feb 05 '26 02:02

Viggo Lundén


1 Answers

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.

like image 176
Amir Popovich Avatar answered Feb 07 '26 22:02

Amir Popovich



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!