2017-03-28 34 views
0

該示例可在@flowtype.org/try找到。在這裏,我期望在兩個示例中使用有條件的類型細化,而它只適用於更簡單的一個。當我引入Array.filter時,提煉不生效。這是Flow中的錯誤還是我的錯誤用法?通過過濾器擊敗的流聯合類型細化

/* @flow */ 

export type Action = 
    {| type: 'ACTION1', payload: string |} 
    | {| type: 'ACTION2', payload: number |} 
    | {| type: 'ACTION3' |} 

const things = (state: Array<number> = [], action: Action): Array<number> => { 
    if (action.type === 'ACTION2') { 
    return state.filter((thing) => { return thing !== action.payload }) 
    } else { 
    return state 
    } 
} 

things([1, 5], { type: 'ACTION2', payload: 5 }) 

const add = (state: number = 0, action: Action): number => { 
    if (action.type === 'ACTION2') { 
    return state + action.payload 
    } else { 
    return state 
    } 
} 

add(0, { type: 'ACTION2', payload: 5 }) 

生成以下錯誤:

10:  return state.filter((thing) => { return thing !== action.payload }) 
                   ^property `payload`. Property not found in 
6: | {| type: 'ACTION3' |}  ^object type 

回答

4

這簡直是流動的問題積極無效類型的改進。 Flow不知道filter將如何處理您通過的回叫。也許它會保存並稍後調用它。 Flow也沒有意識到沒有別的東西重新排列action。就其而言,在回調被調用之前,action可能被重新分配到{type: 'ACTION3'}。將負載拉出到const解決了問題:

const payload = action.payload; 
return state.filter((thing) => { return thing !== payload })