Skip to content

Implicit Enum Duplicate Values #6864

Description

@omeid

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

Activity

  1. Arnavion commented on Feb 3, 2016

    @Arnavion
    Contributor

    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.

  2. RyanCavanaugh commented on Feb 3, 2016

    @RyanCavanaugh
    Member

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

  3. omeid commented on Feb 3, 2016

    @omeid
    Author

    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.

  4. added
    Too ComplexAn issue which adding support for may be too complex for the value it adds
    and removed on Mar 15, 2016
  5. RyanCavanaugh commented on Mar 15, 2016

    @RyanCavanaugh
    Member

    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.

  6. locked and limited conversation to collaborators on Jun 19, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    SuggestionAn idea for TypeScriptToo ComplexAn issue which adding support for may be too complex for the value it adds

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions