An Interest In:
Web News this Week
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
Two Simple Tricks for Typing Redux Apps with Typescript
Despite having used Typescript and Redux separately for a few years I haven't always had a good experience putting them together. Recently, I stumbled on two tricks that have helped me immensely.
Generate Reducer Type from Initial State
When you're creating a new reducer you can use typeof
to generate the type for the reducer. When you export your reducer make sure to include that type.
const initialState = { dogs: 4, name: "Callie", colors: ["red", "green", "blue"]};type MyReducer = typeof initialState;export default function myReducer(state = initialState, action): MyReducer { // ...}
If your initial state doesn't include all of the values, you can include them as placeholder values such as null
. In those cases you can use as <type>
to indicate the intended type for that piece of state.
For example const initialState = { person: null as Person };
Export Your Entire Redux State
Once your reducers are all individually typed, you can create and export a combined ReduxState
type using Typescript's ReturnType utility. This type will contain information about every single reducer used in your application.
import { reducers } from "./reducers";export const store = createStore(combineReducers(reducers));export type ReduxState = ReturnType<typeof store.getState>;
Use this to type the state
argument used by your selector functions, mapStateToProps
or anywhere else that may be needed.
import { ReduxState } from "../store";export const getDogs(state: ReduxState) { return state.myReducer.dogs;}
While it doesn't cover typescript (yet!), don't forget to check out my course Redux with React Hooks which shows how much simpler redux becomes when you drop the boilerplate.
What are your favorite typescript tricks when using Redux?
Original Link: https://dev.to/xjamundx/two-simple-tricks-for-typing-redux-apps-with-typescript-1h7f
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To