Closed tpluscode closed 3 years ago
Not sure what benefit variadic parameters add here, what's being passed exactly - an array of strings or an array of string arrays?
Array of strings. What benefit would you have in mind? I though this would allow calling the reducer with a variable number of arguments. reduce(foo)
, reduce(foo, bar)
, etc.
That's not really a benefit - the intent is that each reducer function does a single type of update, handling a single action, not that it acts as a top level reducer expecting varying types of action which it then has to inspect to decide how to handle (that's the Redux way of working).
What you likely need are separate functions for each distinct action and they will then provide the dispatch functions to use, again, with the parameters specific to each.
A parameter could still be optional in theory but I can't think of any use-case that makes sense off-hand.
I think you misunderstood my intent. Here's a little more tangible example, simple reducer to append a varying number of items to a collection
function push(state, ...newItems: string[]) {
return {
...state,
items: [ ...state.items, ...newItems ],
}
}
I check now that it actually does not work and only the first argument passed to dispatch is forwarded to the reducer.
On the other hand an optional parameter, while I have not had such a need yet, could make sense indeed and also suffers a similar issue with the inferred type for the dispatcher interface. Off the top of my head would be something like dispatch.loadingFailed(error)
where the error
is possibly undefined. That, however, can be handler by typing the reducer just slightly differently
-loadingFailed(state: State, error?: Error)
+loadingFailed(state: State, error: Error | undefined)
This works unless one would desire to call this without parameter indeed.
You could use the following to achieve what you want:
push(state, items: string[]) {
return {
...state,
items: [ ...state.items, ...items ],
}
}
When I create a reducer like
The inferred dispatch method is typed a paramterless