Blog>
Snippets

Type Safety with Redux Actions and Reducers

Show how to define type-safe actions and reducers using TypeScript with Redux v5.0.0, enhancing the reliability of Redux-related code.
// ActionTypes.ts
export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';

// Action Creators
export interface IncrementAction {
  type: typeof INCREMENT;
}

export interface DecrementAction {
  type: typeof DECREMENT;
}

export const increment = (): IncrementAction => ({
  type: INCREMENT,
});

export const decrement = (): DecrementAction => ({
  type: DECREMENT,
});

// Actions type
type CounterActions = IncrementAction | DecrementAction;
Defines Redux action types, action creators, and the action type union for type safety using TypeScript.
// Reducer.ts
import { INCREMENT, DECREMENT, CounterActions } from './ActionTypes';

interface CounterState {
  count: number;
}

const initialState: CounterState = {
  count: 0,
};

export const counterReducer = (
  state: CounterState = initialState,
  action: CounterActions
): CounterState => {
  switch (action.type) {
    case INCREMENT:
      return { ...state, count: state.count + 1 };
    case DECREMENT:
      return { ...state, count: state.count - 1 };
    default:
      return state;
  }
};
Defines a type-safe Redux reducer using TypeScript, specifying the initial state, the actions it handles, and the state transitions for each action.
// Store.ts
import { createStore, combineReducers } from 'redux';
import { counterReducer } from './Reducer';

const rootReducer = combineReducers({
  counter: counterReducer,
});

export type AppState = ReturnType<typeof rootReducer>;

export const store = createStore(rootReducer);
Creates a Redux store with the root reducer, combining all individual reducers, and exports a type representing the entire state of the store.