koninos
koninos

Reputation: 5357

Issue with open ended enums in typescript

Typescript Enums are number based and are also open ended. This means that I can have

enum Color {
   Red = 0,
   Green,
   Blue
}

enum Color {
   Black
}

the issue here is that now I have Color.Red associated with value 0 and Color.Black also associated with value 0. I would expect Color.Black to be associated with the next available value which is 3. Obviously the fix is easy but the behavior is strange and it might lead to bugs. Is this an issue of the language or this happens for some other reason?

Upvotes: 0

Views: 93

Answers (1)

Sebastian Sebald
Sebastian Sebald

Reputation: 16866

Seems like a bug in the language. If you omit the initialization for Red TypeScript will throw an error. But if you initialize it it will not.

The output is definitely broken:

enum One {
  Foo = 0,
  Bar
}

enum One {
  Baz
}

will transpile to

var One;
(function (One) {
    One[One["Foo"] = 0] = "Foo";
    One[One["Bar"] = 1] = "Bar";
})(One || (One = {}));
(function (One) {
    One[One["Baz"] = 0] = "Baz";
})(One || (One = {}));

which is obviously not the outcome you want :)

Upvotes: 1

Related Questions