Sub topic 9
Typing the store and hooks with TypeScript
This chapter assumes you know basic TypeScript (interfaces, generics, typeof, ReturnType), have a working store from the earlier chapters, and use React-Redux 9.1 or later. Redux Toolkit ships its own type definitions, so you install nothing extra. The goal is to let the compiler infer as much as possible from the store, so you write very few type annotations by hand.
The problem with untyped hooks
In plain JavaScript, useSelector((state) => state.counter.value) works. In TypeScript, the state parameter has no known type, so you get an error or an implicit any. You could annotate it in every component, but that repeats the state shape everywhere and breaks when the shape changes.
The fix is to derive the types once, from the store, and export typed versions of the hooks.
Deriving RootState and AppDispatch
The store already knows its own state shape from the reducers you gave it. Two type aliases read that information back out.
import { configureStore } from '@reduxjs/toolkit'
import { useDispatch, useSelector } from 'react-redux'
import counterReducer from './counterSlice'
export const store = configureStore({
reducer: { counter: counterReducer },
})
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch
export const useAppDispatch = useDispatch.withTypes<AppDispatch>()
export const useAppSelector = useSelector.withTypes<RootState>()RootStateis the return type ofstore.getState. It is an object with one key per reducer, such as{ counter: { value: number } }.AppDispatchis the type ofstore.dispatch. It includes any middleware you added, which matters for thunks (covered below).useDispatch.withTypes<AppDispatch>()anduseSelector.withTypes<RootState>()return the same hooks with the types fixed.withTypesrequires React-Redux 9.1 or later.
Why you use the typed hooks everywhere
Once you export useAppSelector and useAppDispatch, import them in components instead of the plain hooks.
import { useAppDispatch, useAppSelector } from './store'
import { incremented, amountAdded } from './counterSlice'
export function Counter() {
const value = useAppSelector((state) => state.counter.value)
const dispatch = useAppDispatch()
return (
<div>
<span>{value}</span>
<button onClick={() => dispatch(incremented())}>+1</button>
<button onClick={() => dispatch(amountAdded(5))}>+5</button>
</div>
)
}Here state is inferred as RootState, so state.counter.value autocompletes and is checked as a number. A typo such as state.counter.vlaue becomes a compile error. Passing a string to amountAdded also fails, once the slice is typed as shown in the next section.
Keep the typed hooks in one file, often hooks.ts or the store file itself. A common error is importing from react-redux by habit in one component. That component then loses type checking, and nothing warns you.
Typing slice state and action payloads
createSlice infers state from initialState. That is enough when the initial value shows the whole shape. It is not enough when a field starts empty, because null or [] gives TypeScript too little to work with.
import { createSlice, type PayloadAction } from '@reduxjs/toolkit'
interface User {
id: number
name: string
}
interface SessionState {
user: User | null
tags: string[]
}
const initialState: SessionState = {
user: null,
tags: [],
}
const sessionSlice = createSlice({
name: 'session',
initialState,
reducers: {
signedIn(state, action: PayloadAction<User>) {
state.user = action.payload
},
tagAdded(state, action: PayloadAction<string>) {
state.tags.push(action.payload)
},
signedOut(state) {
state.user = null
},
},
})
export const { signedIn, tagAdded, signedOut } = sessionSlice.actions
export default sessionSlice.reducerTwo points matter here.
- Declare the state type on the
initialStateconstant (const initialState: SessionState). Without it,user: nullis inferred asnull, and assigning aUserfails. PayloadAction<T>types theactionargument. The generated action creator then requires aT. ForsignedIn, callingsignedIn({ id: 1, name: 'Ada' })compiles, andsignedIn('Ada')does not. ForsignedOut, which has noactionparameter, the creator takes no argument.
If a payload is optional, use PayloadAction<string | undefined>. If an action has no payload, leave out the second parameter instead of typing it as void.
Typing selectors
A selector written as a standalone function needs RootState on its parameter, because it is not inside a hook callback that supplies the type.
import { createSelector } from '@reduxjs/toolkit'
import type { RootState } from './store'
export const selectTags = (state: RootState) => state.session.tags
export const selectUser = (state: RootState) => state.session.user
export const selectTagCount = createSelector([selectTags], (tags) => tags.length)createSelector infers the result function's parameters from the input selectors. Here tags is string[] without any annotation.
A circular import can appear. The slice file imports RootState from the store file, and the store file imports the reducer from the slice file. This is safe when you only use import type, because type imports are erased at compile time. It becomes a problem if a slice needs a runtime value from the store file. Keep that direction one-way in practice: types flow from the store to the slices, and values flow from the slices to the store.
Typing thunks
A thunk created with createAsyncThunk needs to know the types of its argument, its return value, and sometimes its thunkAPI. The first two are inferred from the payload creator.
import { createAsyncThunk } from '@reduxjs/toolkit'
import type { RootState } from './store'
interface Todo {
id: number
title: string
completed: boolean
}
export const fetchTodoById = createAsyncThunk<
Todo,
number,
{ state: RootState; rejectValue: string }
>('todos/fetchById', async (id, { getState, rejectWithValue }) => {
const response = await fetch(`/api/todos/${id}`)
if (!response.ok) {
return rejectWithValue(`Request failed with status ${response.status}`)
}
return (await response.json()) as Todo
})The three generic arguments are the return type, the argument type, and a config object. In the config, state types getState(), and rejectValue types the payload you pass to rejectWithValue. Because AppDispatch comes from a store that includes the thunk middleware, dispatch(fetchTodoById(1)) is accepted. The plain Dispatch type from Redux does not accept thunks, which is why useAppDispatch matters.
How the types flow
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `state` is `unknown` or `any` in a selector | Plain `useSelector` used | Use `useAppSelector` |
| Cannot assign a `User` to `null` | `initialState` has no declared type | Annotate the constant with the state interface |
| Thunk not assignable to action | Plain `useDispatch` used | Use `useAppDispatch` |
| `withTypes` does not exist | React-Redux older than 9.1 | Upgrade, or annotate each hook call by hand |
| Circular import error at runtime | Slice imports a value from the store file | Use `import type` for `RootState` |
Older React-Redux versions
Before 9.1, you created typed hooks by assigning a typed alias:
import { useDispatch, useSelector } from 'react-redux'
import type { TypedUseSelectorHook } from 'react-redux'
import type { RootState, AppDispatch } from './store'
export const useAppDispatch: () => AppDispatch = useDispatch
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelectorThis does the same job. Prefer withTypes when your version supports it.
Exercise
A slice declares initialState = { user: null } with no type annotation. Inside a reducer, state.user = action.payload fails to compile when the payload is a User. Why does it fail, and what is the fix?
Show answer
TypeScript infers the type of user as null from the initial value, so no other value can be assigned to it. Define an interface such as interface SessionState { user: User | null } and annotate the constant: const initialState: SessionState = { user: null }.
Exercise
A component calls dispatch(fetchTodoById(1)) using useDispatch from react-redux, and the compiler rejects it. Which exported hook should replace it, and why does it accept the thunk?
Show answer
Use useAppDispatch. It is typed with AppDispatch, which is typeof store.dispatch. That type includes the thunk middleware, so it accepts functions as well as plain actions.