Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implicit conversion of number to const enum #6131

Closed
crobi opened this issue Dec 17, 2015 · 1 comment
Closed

Implicit conversion of number to const enum #6131

crobi opened this issue Dec 17, 2015 · 1 comment
Labels
By Design Deprecated - use "Working as Intended" or "Design Limitation" instead Question An issue which isn't directly actionable in code

Comments

@crobi
Copy link

crobi commented Dec 17, 2015

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.

@ahejlsberg
Copy link
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.

@ahejlsberg ahejlsberg added the Question An issue which isn't directly actionable in code label Dec 17, 2015
@DanielRosenwasser DanielRosenwasser added the By Design Deprecated - use "Working as Intended" or "Design Limitation" instead label Dec 17, 2015
@mhegazy mhegazy closed this as completed Jan 5, 2016
@ghost ghost mentioned this issue Jul 10, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
By Design Deprecated - use "Working as Intended" or "Design Limitation" instead Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

4 participants