Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 41 ยท Testing and Tooling

TypeScript with Redux Toolkit

Type a Redux Toolkit app: infer RootState and AppDispatch from the store, create typed hooks with withTypes, type slices, PayloadAction, createAsyncThunk and RTK Query endpoints.

Redux Toolkit is written in TypeScript and is designed so that you write very few type annotations: most types are inferred from the code you already have. The recipe is short: infer RootState and AppDispatch from the store, build typed hooks once, annotate each slice's state, and annotate action payloads with PayloadAction. This lesson walks through it and then lets you run the key typing ideas on our TypeScript runner using hand-written stand-ins (the Redux packages themselves are not available there).

The store: infer, do not write by hand

TypeScript
// Real Redux Toolkit code (read-only): app/store.ts
import { configureStore } from '@reduxjs/toolkit';
import todosReducer from '../features/todos/todosSlice';
import authReducer from '../features/auth/authSlice';

export const store = configureStore({
  reducer: { todos: todosReducer, auth: authReducer },
});

// Infer the types from the store itself
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
export type AppStore = typeof store;

When you add a slice, RootState updates by itself. AppDispatch is important because the store's dispatch knows about thunk middleware, so dispatch(fetchTodos()) type-checks, while the plain Dispatch type from Redux does not.

Typed hooks, once

Never import useSelector and useDispatch straight from react-redux in components. Define pre-typed versions once (RTK 2 / React-Redux 9 withTypes API):

TypeScript
// Real React-Redux code (read-only): app/hooks.ts
import { useDispatch, useSelector, useStore } from 'react-redux';
import type { AppDispatch, AppStore, RootState } from './store';

export const useAppDispatch = useDispatch.withTypes<AppDispatch>();
export const useAppSelector = useSelector.withTypes<RootState>();
export const useAppStore = useStore.withTypes<AppStore>();

In components: const items = useAppSelector((state) => state.todos.items); has the right type with no annotations, and a typo such as state.todo.items is a compile error.

Typing a slice

Declare an interface for the slice state, give initialState that type, and use PayloadAction<T> for actions that carry data.

TypeScript
// Real Redux Toolkit code (read-only): features/todos/todosSlice.ts
import { createSlice, type PayloadAction } from '@reduxjs/toolkit';

export interface Todo {
  id: number;
  text: string;
  done: boolean;
}

interface TodosState {
  items: Todo[];
  filter: 'all' | 'done' | 'open';
}

const initialState: TodosState = { items: [], filter: 'all' };

const todosSlice = createSlice({
  name: 'todos',
  initialState,
  reducers: {
    todoAdded(state, action: PayloadAction<Todo>) {
      state.items.push(action.payload);
    },
    filterSet(state, action: PayloadAction<TodosState['filter']>) {
      state.filter = action.payload;
    },
    cleared: (state) => { state.items = []; },   // no payload: no PayloadAction
  },
});

export const { todoAdded, filterSet, cleared } = todosSlice.actions;
export default todosSlice.reducer;

With this, todoAdded({ id: 1, text: 'a', done: false }) is checked, todoAdded('oops') is an error, and cleared() takes no argument. Use prepare callbacks for actions whose payload is computed (ids, timestamps), and a union literal type ('all' | 'done' | 'open') instead of string wherever the values are a closed set.

Typing thunks and async thunks

TypeScript
// Real Redux Toolkit code (read-only)
import { createAsyncThunk } from '@reduxjs/toolkit';
import type { RootState, AppDispatch } from '../../app/store';

// Define pre-typed createAsyncThunk once
export const createAppAsyncThunk = createAsyncThunk.withTypes<{
  state: RootState;
  dispatch: AppDispatch;
  rejectValue: { message: string };
}>();

export const fetchTodos = createAppAsyncThunk('todos/fetch', async (userId: number, { getState, rejectWithValue }) => {
  const { auth } = getState();                      // typed as RootState
  const res = await fetch(`/api/users/${userId}/todos`, { headers: { Authorization: auth.token ?? '' } });
  if (!res.ok) return rejectWithValue({ message: `HTTP ${res.status}` });
  return (await res.json()) as Todo[];              // action.payload type of fulfilled
});

The argument type (userId: number) is read from the payload creator's first parameter; the return type becomes fulfilled.payload; rejectValue types rejected.payload. In a slice's extraReducers, action.payload on fetchTodos.fulfilled is then correctly Todo[].

RTK Query

Types for endpoints come from two generics: build.query<ResultType, ArgType>.

TypeScript
// Real Redux Toolkit code (read-only)
export const api = createApi({
  reducerPath: 'api',
  baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
  tagTypes: ['Post'],
  endpoints: (build) => ({
    getPost: build.query<Post, number>({ query: (id) => `/posts/${id}`, providesTags: ['Post'] }),
    addPost: build.mutation<Post, Partial<Post>>({ query: (body) => ({ url: '/posts', method: 'POST', body }), invalidatesTags: ['Post'] }),
  }),
});
// useGetPostQuery(3) -> data: Post | undefined ; useGetPostQuery('x') is an error

Typing ideas you can run

The following examples use no Redux packages. They show the same TypeScript techniques that RTK relies on: discriminated unions for actions, a state type that is inferred from the reducer, and ReturnType to derive a RootState.

TypeScript Typed actions and inferred state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The switch is exhaustive: the function has no default, and TypeScript knows every case returns a State. If you add a new member to Action and forget a case, the compiler reports that the function does not return a value for all code paths.

TypeScript Deriving RootState and a typed dispatch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Uncomment the last two lines to see the compile errors the runner reports. In a real Redux Toolkit store you get the same safety on dispatch, plus the extra thunk overload.

Common TypeScript problems

  • state is any in useSelector: you used the untyped hook. Use useAppSelector.
  • "Type instantiation is excessively deep": usually a circular import between the store and a slice that imports RootState. Import types with import type, and avoid importing the store file from slices (use getState in thunks via createAppAsyncThunk instead).
  • Optional state fields: declare error: string | null, not error?: string; null is explicit and serializable.
  • Action payload undefined: PayloadAction<void> makes cleared() callable with no argument.
  • Non-serializable types (Date, Map) fail the dev check at runtime: type fields as string (ISO) or number.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How should RootState be defined?

    Inferring it means it updates automatically with new slices.
  2. 2. Why define useAppSelector and useAppDispatch?

    withTypes pre-applies the generics once.
  3. 3. How is an action that carries a number typed in a slice reducer?

    PayloadAction<T> is { type, payload: T }.
  4. 4. What does the discriminated union on the type field give a switch statement?

    TypeScript knows the shape of the action inside each case.

Summary

  • Infer RootState and AppDispatch from the store; do not hand-write them.
  • Create useAppSelector, useAppDispatch and a pre-typed createAsyncThunk once.
  • Type slice state with an interface and payloads with PayloadAction<T>.
  • RTK Query endpoints take <ResultType, ArgType>.
  • Discriminated unions and exhaustive switches make plain reducers safe too.

Next: Migrating to Redux Toolkit