Skip to content

Enum can be assigned out-of-bounds values #30629

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

Closed
jrieken opened this issue Mar 28, 2019 · 4 comments
Closed

Enum can be assigned out-of-bounds values #30629

jrieken opened this issue Mar 28, 2019 · 4 comments
Labels
Duplicate An existing issue was already created

Comments

@jrieken
Copy link
Member

jrieken commented Mar 28, 2019

TypeScript Version: 3.4.0-rc

const enum Fonum  {
    a = 1,
    b = 2
}

let value: Fonum = 12; // no error?
let value2: 1 | 2 = 12; // error

https://www.typescriptlang.org/play/#src=const%20enum%20Fonum%20%20%7B%0D%0A%20%20%20%20a%20%3D%201%2C%0D%0A%20%20%20%20b%20%3D%202%0D%0A%7D%0D%0A%0D%0Alet%20value%3A%20Fonum%20%3D%2012%3B%20%2F%2F%20no%20error%3F%0D%0A%0D%0Alet%20value2%3A%201%20%7C%202%20%3D%2012%3B%20%2F%2F%20error

@dragomirtitian
Copy link
Contributor

I believe this is by design as stated by @DanielRosenwasser in #26362 to allow for bitwise operations on flag enums:

The behavior is motivated by bitwise operations. There are times when SomeFlag.Foo | SomeFlag.Bar is intended to produce another SomeFlag. Instead you end up with number, and you don't want to have to cast back to SomeFlag.
I think if we did TypeScript over again and still had enums, we'd have made a separate construct for bit flags.

@jrieken
Copy link
Member Author

jrieken commented Mar 28, 2019

bitwise operations on flag enums:

That makes sense but then they should geek out and understand that you cannot produce 12 with 1 and/or 2

@dragomirtitian
Copy link
Contributor

@jrieken Challenge accepted 😄 :

let value: Fonum = Fonum.a << Fonum.b << Fonum.a  |  Fonum.a << Fonum.b; // 12

I think it is difficult to tell if the resulting number is valid or not if we consider flag enums and the whole range of bitwise operations.

@jrieken
Copy link
Member Author

jrieken commented Mar 28, 2019

haha - fair point. There should probably be strict enum that doesn't allow these things...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants