Search code examples
typescripttypescript-typingstsc

Duplicate string values in TS enum does not cause compilation error?


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.


Solution

  • 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