将Flow联合类型用于Redux操作 [英] Using Flow union types for Redux actions
问题描述
遵循
Following the style of this Facebook app sample using Redux and Flow together, I made an action type in this manner:
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 }
;
但是我发现,当我尝试使用化简器处理动作时,Flow会抱怨是否尝试访问name
或progress
属性,并说在对象类型中找不到属性".
But I've found that when I try to process my actions with a reducer, Flow complains if I try to access the name
or progress
properties, saying "Property not found in object type".
也就是说,在我的精简器中,如果我检查action.type === 'HANDLE_IMAGE_PUBLISHED'
然后访问action.name
,Flow会抱怨.当访问action.type === 'SET_IMAGE_UPLOAD_PROGRESS'
时,访问action.progress
属性的情况也一样.据我所知,这两种属性访问在各自情况下均应合法,但Flow抱怨.
That is, in my reducer, if I check that action.type === 'HANDLE_IMAGE_PUBLISHED'
and then access action.name
, Flow complains. And the same thing goes for for accessing action.progress
property when action.type === 'SET_IMAGE_UPLOAD_PROGRESS'
. Both these property accesses should be legit under their respective circumstances, as far as I can tell, but Flow complains.
尽管出于某种原因,我可以在任何地方访问action.id
,即使我联合中的一种类型未指定id
属性.我很困惑.
Yet for some reason it's OK for me to access action.id
anywhere, even though one of the types in my union doesn't specify an id
property. I'm very confused.
这是Flow REPL中的实时演示.我在做什么错了?
推荐答案
这只是类型优化无效的情况:
This is simply a case of a type refinement invalidation:
https://flow.org/en/docs/lang/refinements/#toc-refinement-invalidations
因为您正在回调中使用该值,所以Flow悲观地假设您可以在回调运行之前重新分配action
(它不知道map
回调会立即被调用).它也没有做分析就没有位置,实际上是您已重新分配它.
Because you are using the value in a callback, Flow pessimistically assumes that you could have re-assigned action
before the callback runs (it does not know that the map
callback is called immediately). It also does not do the analysis to see that there is no place, in fact, that you re-assign it.
所需要做的就是将action
拔出为const
:
All that's needed is to pull the action
out as a const
:
export default (state: Array<ImageRecordModel> = [], action_: Action): Array<ImageRecordModel> => {
const action = action_;
( tryflow链接)
您可能还需要考虑在.flowconfig
中启用const参数.基本上可以满足您的期望:将所有参数视为const
:
You may also want to consider enabling const params in your .flowconfig
. This does basically what you expect: treats all params as const
:
[options]
experimental.const_params=true
这篇关于将Flow联合类型用于Redux操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!