【问题标题】:Flow union type refinement defeated by filter流联合类型细化被过滤器击败
【发布时间】:2017-03-29 01:51:07
【问题描述】:

例子可以在@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

【问题讨论】:

    标签: javascript flowtype


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-25
      • 2011-01-14
      • 2011-04-09
      • 1970-01-01
      • 2018-11-04
      • 1970-01-01
      • 2015-09-19
      • 2018-04-15
      相关资源
      最近更新 更多