Typing Redux
In this page:
Defining Redux State
Defining Redux state starts with a typed interface for the slice's shape, which becomes the return type of its reducer and the type every component reading from that slice can rely on.
Example: Defining Redux State
interface CounterState {
value: number;
}
const initialState: CounterState = { value: 0 };
function counterReducer(state = initialState, action: { type: string }): CounterState {
return state;
}
console.log(counterReducer(undefined, { type: "init" }));
Typing Payloads
Typing action payloads means each action's payload field has its own specific type matching what that action actually carries, so dispatching an action with the wrong payload shape is caught before runtime.
Example: Typing Payloads
interface IncrementAction {
type: "increment";
payload: number;
}
const action: IncrementAction = { type: "increment", payload: 5 };
console.log(action);
Typing the Redux Store
Typing the store itself usually means exporting RootState (inferred from the store's own getState) and AppDispatch types, which every typed hook in the app then reuses instead of redefining.
Example: Typing the Redux Store
interface RootState {
counter: { value: number };
}
// type AppDispatch = typeof store.dispatch;
const state: RootState = { counter: { value: 0 } };
console.log(state);
Typed React Redux Hooks
Typed React-Redux hooks are built by wrapping the generic useSelector and useDispatch with your app's specific RootState and AppDispatch types, so every component gets fully typed access without repeating generics.
Example: Typed React Redux Hooks
interface RootState {
counter: { value: number };
}
// const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
function selectCount(state: RootState): number {
return state.counter.value;
}
console.log(selectCount({ counter: { value: 3 } }));
Typing Selectors and Redux Data
Typing selectors means annotating their input as RootState and their return type as whatever specific slice or derived value they extract, catching a typo in a state path immediately instead of returning silent undefined.
Example: Typing Selectors and Redux Data
interface RootState {
user: { name: string } | null;
}
function selectUserName(state: RootState): string | undefined {
return state.user?.name;
}
console.log(selectUserName({ user: { name: "Ravi" } }));
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: