错误的结论:“此条件将始终返回'false'”

时间:2019-01-03 09:10:14

标签: typescript

enum State {
  ONE,
  TWO
}

const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))

class StateMachine {
  private state: State = State.ONE

  public async transitionA() {
    this.state = State.TWO
    await sleep(1000)
    if (this.state === State.ONE) { // <-- error
      console.log("It totally happened")
      this.state = State.TWO
    }
  }

  public async transitionB() {
    this.state = State.ONE
  }
}
const stateMachine = new StateMachine()
stateMachine.transitionA()
stateMachine.transitionB()

在指定的行上出现以下编译错误:

Error:(14, 9) TS2367: This condition will always return 'false' since the types 'State.TWO' and 'State.ONE' have no overlap.

但是,在以上示例中,条件为true。这是编译器中的错误/功能吗?有没有解决的办法?

1 个答案:

答案 0 :(得分:2)

这是“控制流分析”的局限性,您可以在其中here中阅读有关该局限性的更多信息

最简单的解决方案是使用类型断言来迫使编译器认为state只是State而不是枚举文字类型State.ONE

public async transitionA() {
    this.state = State.TWO as State
    await sleep(1000)
    if (this.state === State.ONE) { // <-- error
    console.log("It totally happened")
    this.state = State.TWO
    }
}