Typing actions and action payloads for redux-toolkit
Redux-toolkit helps us to significantly reduce boilerplate in the redux layer of our applications. If you’re not familiar with redux-toolkit you can reference official documentation.
Let create a simple todo reducer:
One downside of this code, is that it’s not possible to reuse types of actions and action payloads setTodoStatus
and removeTodo
. For example if you need to reuse action type in a middleware handler (e.g. redux-saga
). One simple solution would be to extract those as separate types:
However, this once again increases boilerplate. Another option would be to use ReturnType
utility to retrieve action return type from the payload creator:
This however make verbose code of the middleware, also this strategy isn’t good if we want to reuse just payload type (for example a utility that should prepare a payload for action). To do that we should get the type on key payload
of the action type. But it looks even worse than example before:
However there’s a way to automatically map all action creator types to action and action payloads types. To do that we need to have a generic utility. What we need is to achieve a map of action creators and transform it to actions or action payloads map. Once again we’ll use ReturnType
utility to achieve that:
And within those utilities we can easily create desired types in an automatic fashion:
I would prefer to reference type asPayloads.setTodoStatus
, however TS doesn’t like this syntax.
A final note, is that setTodoStatus
type is camel case, and it would be nice to capitalize it. I find it amazing, that TS 4 allows us to do so, by the ability to manipulate objects keys and Capitalize
utility:
Hope you found above helpful. Have a good day :)