Blog>
Snippets

Creating Type-Safe Reducers with TypeScript

Show an example of creating a type-safe reducer using TypeScript with Redux Toolkit 2.0's enhanced type inference capabilities.
import { createSlice, PayloadAction } from '@reduxjs/toolkit';

// Define a type for the slice state
interface CounterState {
  value: number;
}

// Define the initial state using that type
const initialState: CounterState = {
  value: 0
};

export const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    // Use the PayloadAction type to declare the contents of `action.payload`
    increment: state => {
      state.value += 1;
    },
    decrement: state => {
      state.value -= 1;
    },
    // The `PayloadAction` type can be parameterized with the type of `action.payload`
    incrementByAmount: (state, action: PayloadAction<number>) => {
      state.value += action.payload;
    },
  },
});

// Export actions
export const { increment, decrement, incrementByAmount } = counterSlice.actions;

// Export reducer
export default counterSlice.reducer;
This example demonstrates how to create a type-safe reducer with TypeScript using Redux Toolkit's createSlice function. The CounterState interface declares the shape of the state for the slice, and the initialState variable initializes the state. Within the slice, reducers are defined with clear typing for the payload of actions, ensuring type safety and better developer experience.