ReduxJS/Toolkit: TypeScript
How to keep all this type-safe

You don’t want to be using useDispatch, useSelector etc directly in your code. Instead they are wrapped so that you can enjoy complete type safety!

Category:

javascript

Tags:

reacttutorial

Share this article on:

A futuristic AI engineer meticulously assembling complex, interconnected digital components inside a glowing cybernetic workspace. Holographic interfaces float around, displaying intricate patterns of structured data and system logic. The environment is sleek and futuristic, radiating an aura of precision and technological mastery.

TypeScript Hooks

import { configureStore } from "@reduxjs/toolkit";
import { useDispatch, useSelector } from "react-redux";

const store = configureStore({});
export type AppDispatch = typeof store.dispatch;
export const useAppDispatch = useDispatch.withTypes<AppDispatch>();

export type RootState = ReturnType<typeof store.getState>;
export const useAppSelector = useSelector.withTypes<RootState>();

createAsyncThunk

More info

import { Action, createAsyncThunk, ThunkAction } from "@reduxjs/toolkit";
export type AppThunk<ThunkReturnType = void> = ThunkAction<ThunkReturnType, RootState, unknown, Action>;
export const createAppAsyncThunk = createAsyncThunk.withTypes<{state: RootState, dispatch: AppDispatch}>();

// Complete example:
const createAppAsyncThunk = createAsyncThunk.withTypes<{
  state: RootState
  dispatch: AppDispatch
  rejectValue: string
  extra: { whatever: number }
}>()

createSelector

// Wrapping reselect createSelector
import { createSelector } from "@reduxjs/toolkit";
const createAppSelector = createSelector.withTypes<RootState>();

Also in this series

Extras

Stuff that came into being during the making of this post