首页 文章

Flow(类型)不尊重我为类属性做的手动检查

提问于
浏览
0

一个例子:

class MyClass {
  foo: ?string;
  constructor(foo) {
    this.foo = foo;
  }

  doSomething() {
    if (!this.foo) throw new Error();
    console.log('hi'); // if I comment this line, I get no errors!
    const myFoo: string = this.foo;
  }
}

我收到以下错误:

12:const myFoo:string = this.foo; ^无法将this.foo分配给myFoo,因为null或undefined 1与string [2]不兼容 .

你可以看到它here .

如您所见,我确保设置了 this.foo . 但是,如果在检查之后,执行了任何代码,尽管该代码没有执行任何操作,它会忽略我的检查 .

2 回答

  • 1

    这是由Flow的Refinement Validations引起的

    这也提供了一个示例解决方法 .

    只读变量不一定是不可变的 . 例如, delete this.foo 不会导致错误(这可能是流程中的错误,因为它似乎明显违反了类型,但与重新分配不同 - bug report) .

  • 1

    Flow不允许这样做,因为就它而言, console.log() 调用可以改变 this.foo 的值,这是正确的 . 理论上,Flow可以是特殊情况 console.log ,因为它不喜欢有副作用,但它可能是真正的任何函数调用 . 如果你希望这个工作,你需要先获取值,例如

    doSomething() {
      const foo = this.foo;
      if (!foo) throw new Error();
      console.log('hi');
      const myFoo: string = foo;
    }
    

    要么

    doSomething() {
      if (!foo) throw new Error();
      const foo = this.foo;
      console.log('hi');
      const myFoo: string = foo;
    }
    

    因为 foo 变量的类型无法更改,因为它不会在任何地方重新分配 .

相关问题