2017-02-11 26 views
0

我最近將Flow應用於我的React Native項目。到目前爲止,大多數事情都是可以滿足的。使用Flow類型檢查調用連續可空對象的方法

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; 

有沒有適當的方法來處理這種情況?我不想在這裏使用壓制評論,因爲它不是一個特例。

+0

https://flowtype.org/try/#0MYGwhgzhAEAK4E8CmAnA3gXwFCkjAgtGltNAA6KoBcA-NAPIBGAVksAC7QC80AdkgHc4lFAAoAlAG4S0ALYSiM0iCScKYZCm7R2ACwCWEAHTrN00qX0AzaKNOpxiixfsojEdgHsyE88-IiRgAmSB4ongi+Si4i2rwAriAgfqTYqVgYQA –

+1

'讓玩家對象=新播放器()'應該是'讓球員:??對象=新播放器()' –

回答

2

流對於類型優化(例如空檢查)很不樂觀。

在您的示例中,Flow不知道對this.player.stop()的調用是否設置爲this.playernullundefined。正因爲如此,它必須假設它可能會使精化無效。

通常我解決這個拉性能進行到一個局部變量,並在該操作:

let player ?Object = new Player(); 
const constPlayer = this.player; 
if (constPlayer) { 
    constPlayer.stop(); 
    constPlayer.destroy(); 
    this.player = null; 
} 

這是一個小更詳細的,但它不是每次做一個單獨的空檢查的那樣糟糕。

查看dynamic type tests caveats部分了解更多信息。