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

Comparing numeric enum to number narrows variable to 'never' #42442

Closed
ajafff opened this issue Jan 21, 2021 · 1 comment Β· Fixed by #42472
Closed

Comparing numeric enum to number narrows variable to 'never' #42442

ajafff opened this issue Jan 21, 2021 · 1 comment Β· Fixed by #42472
Assignees
Labels
Bug A bug in TypeScript Fix Available A PR has been opened for this issue Rescheduled This issue was previously scheduled to an earlier milestone

Comments

@ajafff
Copy link
Contributor

ajafff commented Jan 21, 2021

Bug Report

πŸ”Ž Search Terms

enum, number, never

πŸ•— Version & Regression Information

  • This changed between versions 3.8.3 and 3.9.7

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

enum E {
    a = 1,
    b = 2,
}

declare let v: E;
if (v !== 0) {
    v &= E.a;
}

πŸ™ Actual behavior

v is narrowed to never inside the IfStatement. The compound assignment gives a compile error: Type 'number' is not assignable to type 'never'.(2322)

πŸ™‚ Expected behavior

v is still of type E and there's no error.

@RyanCavanaugh RyanCavanaugh added the Bug A bug in TypeScript label Jan 21, 2021
@RyanCavanaugh RyanCavanaugh added this to the Backlog milestone Jan 21, 2021
@ahejlsberg ahejlsberg self-assigned this Jan 23, 2021
@ahejlsberg
Copy link
Member

ahejlsberg commented Jan 23, 2021

The issue here is the oddball rule we have (for backwards compatibility reasons) that values of type number are assignable to any enum literal type. This rule also extends to the comparable relationship, meaning that any value of type number is comparable to any enum literal type. Where this gets us into trouble is when we use comparability to filter types in control flow analysis. In this specific example, we filter the type of v by removing everything that isn't comparable to 0--but because of the rule, every value in the enum is comparable to 0, and thus we're left with never. Nonsense!

I think the solution is to remove the strange rule from the comparable relationship. That will cause the example to error on the if conditional with the diagnostic "This condition will always return 'true' since the types 'E' and '0' have no overlap." Which is the behavior we want (as it is indeed true).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug A bug in TypeScript Fix Available A PR has been opened for this issue Rescheduled This issue was previously scheduled to an earlier milestone
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants