Redux With Typescript
Here, I’d like to share my way of using Redux with TypeScript.
I’ll use a plain todo app for the sake of example.
The state interface
I like to centralize what my state looks like in a single interface which will be the source of truth
I can then reference it anywhere, such as in the react-redux connect function:
`connect((state: ReduxState) => ({ todos: state.todos }))`
The action types
I like to use enums for the action types. It also plays well with the editor’s auto-suggest.
The action creators
The creators are plain functions. Note that I do not add a return type for them. I’ll rely on Typescript inference for that.
Note that I force cast the type as being a specific value instead of just a string. This will help TypeScript differentiate the different actions by their types.
The reducers
This is where it all comes together and where you can really use TypeScript to trigger on any erros, such as using an action payload that does not match its action type.
Because the store has been thoroughly typed, you can rely on the auto-suggest to let you know what an action looks like based on its type. If you use a wrong type or associate a wrong payload to it, Typescript will trigger.
Conclusion
This small example demonstrates the power of Typescript to help you leverage your Redux apps. Typescript will create a much-needed faithful map of the state, so you know exactly what your Redux store looks like.