使用Flow联合类型进行Redux操作

时间:2017-04-12 17:41:54

标签: redux flowtype

遵循使用Redux和Flow的this Facebook app sample样式,我以这种方式创建了一个动作类型:

type Action =
  | { type: 'ADD_FILES', files: Array<{ id: number, file: File }> }
  | { type: 'HANDLE_IMAGE_PUBLISHED', id: number, name: string }
  | { type: 'SET_IMAGE_UPLOAD_PROGRESS', id: number, progress: number }
;

但是我发现当我尝试使用reducer处理我的操作时,如果我尝试访问nameprogress属性,则会出现流量抱怨,说&#34;属性不是在对象类型中找到&#34;。

也就是说,在我的reducer中,如果我检查action.type === 'HANDLE_IMAGE_PUBLISHED'然后访问action.name,Flow就会抱怨。在action.progress时访问action.type === 'SET_IMAGE_UPLOAD_PROGRESS'属性也是一样的。据我所知,这些财产访问在各自的情况下应该是合法的,但Flow抱怨。

但出于某种原因,我可以在任何地方访问action.id,即使我的联盟中的某个类型没有指定id属性。我很困惑。

Here is a live demo in the Flow REPL。我做错了什么?

1 个答案:

答案 0 :(得分:4)

这只是一种类型细化失效的情况:

https://flow.org/en/docs/lang/refinements/#toc-refinement-invalidations

因为您在回调中使用了该值,所以Flow悲观地假设您可以在回调运行之前重新分配action(它不知道立即调用map回调)。它也没有做分析,看到事实上没有地方重新分配它。

所需要的只是将action作为const拉出来:

export default (state: Array<ImageRecordModel> = [], action_: Action): Array<ImageRecordModel> => {
  const action = action_;

tryflow link

您可能还想考虑在.flowconfig中启用const params。这基本上符合您的期望:将所有参数视为const

[options]
experimental.const_params=true
相关问题