Skip to content

Implicit conversion of number to const enum #6131

Closed

Description

The following code compiles, even though variable n obviously is assigned value that is incompatible with its type.

const enum BinaryDigit {
    zero = 0,
    one = 1
}

let n: BinaryDigit = 2;

Is there any reason why the compiler allows an implicit conversion of numbers to const enums?

An instance of a base class cannot be implicitly converted to an instance of a derived class. I would have expected the same for const enums and numbers (all const enum values "are" numbers, but not all numbers "are" const enum values). If you do not consider numbers and const enum values equialent types, that would be even more reason to disallow implicit conversion.

Activity

  1. ahejlsberg commented on Dec 17, 2015

    @ahejlsberg
    Member

    It's to allow patterns such as n = n + 1. We actually take the view that all numbers are enum values, but that one enum value is not assignable to another enum value. In other words, numbers and enums implicitly convert to each other, but different enums do not.

    It is obviously possible to construct stricter views of enum types, but those stricter views also often force you to write type assertions. It's all about which compromises you prefer.

  2. 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

    By DesignDeprecated - use "Working as Intended" or "Design Limitation" insteadQuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions