microsoft / TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
https://www.typescriptlang.org
Apache License 2.0
100.41k stars 12.41k forks source link

Implicit Enum Duplicate Values #6864

Closed omeid closed 8 years ago

omeid commented 8 years ago

Enum value incrementation does not consider previously defined values, nor does the compiler throws an error on duplicate values.

Which means you can end up with potential bugs:

enum Color {Red = 3, Green = 2, Blue};

Color.Red == Color.Blue; //true
Arnavion commented 8 years ago

I understand it may be surprising, but it's also how enums work in C / C++ / C# so there is precedent for it. If someone wrote that enum specifically with the intention to have Blue === 3, they would not want TS to warn or error about it.

RyanCavanaugh commented 8 years ago

I'm not sure which would be more surprising. I'll bring it up.

omeid commented 8 years ago

I understand the precedent argument but is that the better option?

I would argue that if for:

enum Color {Red = 3, Green = 2, Blue, Ultraviolet};

Color.Red == Color.Blue; //true

The compiler complained about implicit duplicate values and the fix was this:

enum Color {Red = 3, Green = 2, Blue = 3, Ultraviolet};
Color.Red == Color.Blue; //true

Or better yet,

enum Color {Red = 3, Green = 2, Blue = Color.Red, Ultraviolet};
Color.Red == Color.Blue; //true

Or even better:

enum Color {Red = 3, Green = 2, Blue = Red, Ultraviolet};
Color.Red == Color.Blue; //true

It would be more clear and hard to miss any likely bug.

RyanCavanaugh commented 8 years ago

Finally got to this. Combination of too expensive (every member has to check every other member, basically), too rare an error to make, and too precedented in other languages with implicitly-numbered enums.