我最近将 Flow 应用到了我的 React Native 项目中。到目前为止,大部分事情都是令人满意的。
let player ?Object = new Player();
if (this.player) {
this.player.stop();
this.player.destroy();
this.player = null;
}
但是,Flow 希望我做到如下所示。
let player ?Object = new Player();
if (this.player) {
this.player.stop();
}
if (this.player) {
this.player.destroy();
}
this.player = null;
对于这种情况,有没有什么正确的处理方法呢?我不想在这里使用抑制评论,因为这不是一个异常(exception)情况。
最佳答案
Flow 对类型细化(例如 null 检查)持悲观态度。
在您的示例中,Flow 不知道对 this.player.stop()
的调用是否将 this.player
设置为 null
或未定义
。因此,它必须假设它可能,并使细化无效。
通常,我通过将属性拉出到局部变量中并对其进行操作来解决此问题:
let player ?Object = new Player();
const constPlayer = this.player;
if (constPlayer) {
constPlayer.stop();
constPlayer.destroy();
this.player = null;
}
这有点冗长,但并不比每次都进行单独的空检查那么糟糕。
查看 dynamic type tests caveats部分了解更多信息。
关于javascript - 通过 Flow 类型检查调用连续可为 null 的对象的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42174022/