Skip to content

Negative constant enums return number when toString is called #54992

Description

⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.1.6#code/MYewdgzgLgBApmArgWxgFTtAok1BvAKBmJgEEYBeGARgBoiSAhSmAWmoIF8CDRIQANnAB0AkAHMAFA2JQAngAc4IAGYwAylABOASzBSM2XMNIBKeiRjylq9Jig4UJ4VBCbd+yaYLfe4CIIiYlIyVorKau56BvaOyMKM5qHWEXZGTowubtrRXj5AA

💻 Code

const enum TestEnum {
    A = 1,
    B = -1
}

// "string",  "string" 
console.log(
    typeof String(TestEnum.A),
    typeof TestEnum.A.toString()
)

// "string",  "number" 
console.log(
    typeof String(TestEnum.B),
    typeof TestEnum.B.toString()
)

🙁 Actual behavior

Constant enums which use negative numbers will return type of number when .toString() is called.

🙂 Expected behavior

A string type should be returned

Activity

  1. changed the title [-]Negative numbered constant enums return typeof number when toString is called[/-] [+]Negative numbered constant enums return number when toString is called[/+] on Jul 12, 2023
  2. fatcerberus commented on Jul 12, 2023

    @fatcerberus

    If anyone's wondering how this happens, it's because the emit is -1 .toString() - property access has higher precedence than negation. So effectively what happens is this logs the result of typeof -(1..toString()) -- which is number.

  3. changed the title [-]Negative numbered constant enums return number when toString is called[/-] [+]Negative constant enums return number when toString is called[/+] on Jul 12, 2023
  4. RyanCavanaugh commented on Jul 12, 2023

    @RyanCavanaugh
    Member

    I'm honestly shocked this has been shipping since at least 3.3, possibly forever, without getting noticed 😰

  5. fatcerberus commented on Jul 12, 2023

    @fatcerberus

    I don’t think people generally call methods on enum values, since they’re usually just meant to be used as sentinels. Probably even fewer people still use negative values.

  6. locked as resolved and limited conversation to collaborators on Oct 22, 2025
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

    BugA bug in TypeScriptHelp WantedYou can do this

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions