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

Compiler incorrect enum type narrowing when comparing with a computed getter accessor #19638

Closed
jimutt opened this issue Nov 1, 2017 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@jimutt
Copy link

jimutt commented Nov 1, 2017

TypeScript Version: 2.7.0-dev.20171101

enum States {
  State1,
  State2,
  State3
}

class TypeComparisonProblem {

  private num: number

  constructor () {
    this.num = 0
  }

  public operation (): void {
    if (this.state === States.State1) {
      this.num++ // If previous num was 0 the state will now be State2 when checked on next row
      if (this.state === States.State2) { // This lines throws: error TS2365: Operator '===' cannot be applied to types 'States.State1' and 'States.State2'.
        this.num--
      }
    }
  }

  get state (): States {
    if (this.num < 1) return States.State1
    if (this.num < 10) return States.State2
    return States.State3
  }
}

Expected behavior:
The above class should compile without errors.

Actual behavior:
TS2365: Operator '===' cannot be applied to types 'States.State1' and 'States.State2'.
It assumes that the "state" is "State1" due to the comparison (this.state === States.State1) but as the state is computed depending on the private "num" property it could have an other value when accessed the second time.

@ghost
Copy link

ghost commented Nov 1, 2017

See #9998.
I don't think this case is something that we would ever handle as you expect though, since getters that let one property affect another tend to be rare. We wouldn't want to be assuming that any assignment anywhere could change the type of properties or control flow analysis wouldn't be nearly as useful.
Note that the example will work if state() is a method because we don't narrow the types of method results.

@ghost ghost added the Duplicate An existing issue was already created label Nov 1, 2017
@jimutt
Copy link
Author

jimutt commented Nov 1, 2017

@andy-ms Thank you for referring to the discussion, I understand the problem. Closing because of duplicate.

@jimutt jimutt closed this as completed Nov 1, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

1 participant