Using thread pooling types for Redux actions

Following the style of this sample Facebook app using Redux and Flow together, I did this type of action like this:

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 }
;

      

But I found that when I try to process my actions with a reducer, Flow complains if I try to access properties name

or progress

say "Property not found in object type."

That is, in my reducer, if I check what action.type === 'HANDLE_IMAGE_PUBLISHED'

and then access action.name

, the thread is complaining. And the same goes for property access action.progress

when action.type === 'SET_IMAGE_UPLOAD_PROGRESS'

. As far as I can tell, both of these property accesses should be legal in their respective circumstances, but the thread is complaining.

But for some reason it's okay for me to refer to action.id

anywhere, even though one of the types in my union doesn't specify a property id

. I am very confused.

Here is a live demo on the REPL thread . What am I doing wrong?

+3


source to share


1 answer


It's just a case of invalid type qualification:

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

Since you are using the value in the callback, Flow pessimistically assumes that you could re-assign action

before the callback is triggered (it doesn't know that the callback map

is called immediately). He also does not perform analysis to make sure there is really no room for you to re-assign him.

All that is needed is output action

as const

:



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

      

( tryflow link )

You might also consider including const parameters in .flowconfig

. This is basically what you would expect: treats all parameters as const

:

[options]
experimental.const_params=true

      

+3


source







All Articles