Blog>
Snippets

Migrating to UnknownAction from AnyAction

Provide an example of how to adapt existing Redux action types to use `UnknownAction`, enhancing type safety over the previously used `AnyAction` type.
// First, define your action creators using Redux Toolkit
const todoAdded = createAction('todos/todoAdded', function prepare(text) {
  return {
    payload: {
      id: nanoid(),
      text
    }
  };
});

// Define a type guard for your custom action
function isTodoAction(action: unknown): action is ReturnType<typeof todoAdded> {
  return action && typeof action === 'object' && 'type' in action && action.type === todoAdded.type;
}
This code defines a Redux Toolkit action creator and a type guard to check if an action is of the todoAdded action type.
// Then, replace AnyAction with UnknownAction in your reducer signature
import { UnknownAction } from '@reduxjs/toolkit';

const todosReducer = (state: Todo[] = [], action: UnknownAction): Todo[] => {
  // Inside the reducer, use the type guard to narrow down the action type
  if (isTodoAction(action)) {
    // action is now guaranteed to be a PayloadAction with the correct type
    return [...state, action.payload];
  }
  return state;
};
This code updates a reducer to use UnknownAction instead of AnyAction, relying on the type guard to ensure correct action types.
// Utilize the match method provided by Redux Toolkit's action creators
const todosReducerRTK = (state: Todo[] = [], action: UnknownAction): Todo[] => {
  if (todoAdded.match(action)) {
    // With the match method, the payload type is automatically inferred
    return [...state, action.payload];
  }
  return state;
};
This code snippet replaces manual type guards with the match method provided by Redux Toolkit action creators for type-safe reducers.
// Middleware using Redux Toolkit match method
const loggingMiddleware: Middleware<{}, any> = store => next => action => {
  if (todoAdded.match(action)) {
    // Log action only if it's a todoAdded action
    console.log('Adding todo:', action.payload);
  }
  return next(action);
};
Middleware using the match method from Redux Toolkit to log actions of a specific type, thus enhancing the type safety over the deprecated AnyAction.