流联合型细化被过滤器击败

Ben*_*eld 0 javascript flowtype

该示例可以在@ 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 })
Run Code Online (Sandbox Code Playgroud)

产生以下错误:

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

Nat*_*ote 5

这只是 Flow 积极使类型细化无效的问题。Flow 不知道filter将如何处理您传递的回调。也许它会保存它并稍后调用它。Flow 也没有意识到没有其他任何东西重新分配action。就其而言,可能会在调用回调时action重新分配。{type: 'ACTION3'}将有效负载拉出到 a 中const可以解决问题:

const payload = action.payload;
return state.filter((thing) => { return thing !== payload })
Run Code Online (Sandbox Code Playgroud)