10

I have this in a TypeScript enum:

export enum LMXLockRequestError {
  MaxRetries = 'bad_args',
  BadArgumentsError = 'bad_args',
}

this doesn't seem to cause a compilation error. It transpiles to this:

var LMXLockRequestError;
(function (LMXLockRequestError) {
    LMXLockRequestError["MaxRetries"] = "bad_args";
    LMXLockRequestError["BadArgumentsError"] = "bad_args";
})(LMXLockRequestError = exports.LMXLockRequestError || (exports.LMXLockRequestError = {}));

if I were to then use it to do:

if(v === LMXLockRequestError.MaxRetries){

}

if v was 'bad_args' it would match both MaxRetries and BadArgumentsError.

Is this supposed to happen? Or should I file an issue with TypeScript on Github?

To me an enum should have different keys, but maybe not necessarily different values? It would be nice if there was a way to tell the enum that it must have different values.

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817

4 Answers4

8

regarding the TS ENUM specification:

Enums allow us to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.

There is nothing about that it should to be uniq, so probably that behaivor is okey.

enum/typescript

UPDATE: There is another interesting thing about the ENUM and 'bugs':

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
Sh. Pavel
  • 1,584
  • 15
  • 28
3

To add an actual issue you might encounter wit this (remember that at runtime it's the value that is used) :

enum Toto {
   A = "a",
   B = "a"
}

const a = Toto.B;
switch (a) {
    case Toto.A:
        console.log("1");
    break;
    case Toto.B:
        console.log("2");
}

There is no way to enter into case Toto.B case. It would be handy if typescript would NOT allow duplicated names.

ic3
  • 7,917
  • 14
  • 67
  • 115
1

There is an typescript-eslint rule for that : no-duplicate-enum-values.

Matthieu Riegler
  • 31,918
  • 20
  • 95
  • 134
0

The same behaviour happens in c#:

void Main() {
    var blue = Color.Blue;
    blue.Dump(); // Red
}

enum Color {
    Red = 3,
    Green = 2,
    Blue 
}
Donniewiko
  • 1,427
  • 1
  • 8
  • 9