2017-02-11 2 views
0

最近、私のReact NativeプロジェクトにFlowを適用しました。これまでのところ、ほとんどのことが充足されています。フロータイプのチェックで行内にnull可能なオブジェクトのメソッドを呼び出す

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

フローは、タイプの絞り込み(nullチェックなど)に関して悲観的です。

例では、this.player.stop()への呼び出しがthis.playerからnullまたはundefinedに設定されているかどうかがフローには分かりません。それゆえ、それは、それが可能性があると仮定して、洗練を無効にしなければならない。

一般的に、私はローカル変数にプロパティを引き出して、その上で動作させることによってこの問題を回避:

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

これは少しより冗長ですが、それは別のヌルチェックを毎回やっほど悪くはありません。

詳細については、dynamic type tests caveatsのセクションをご覧ください。

関連する問題