Blog>
Snippets

Implementing Type-Safe Middleware with TypeScript

Demonstrate how to write a Redux middleware using TypeScript that enforces type safety for actions and state, ensuring that the middleware only processes specific action types with the appropriate payload structure.
import { MiddlewareAPI, Dispatch, AnyAction } from 'redux';

// Define a specific action type
interface MyCustomAction {
  type: 'MY_CUSTOM_ACTION';
  payload: {
    id: number;
    message: string;
  };
}

// Type guard function to check if an action is MyCustomAction
function isMyCustomAction(action: AnyAction): action is MyCustomAction {
  return action.type === 'MY_CUSTOM_ACTION';
}

// Our middleware will only process `MyCustomAction` and log its payload
const myCustomMiddleware = ({ getState }: MiddlewareAPI) => 
  (next: Dispatch<AnyAction>) => 
  (action: AnyAction) => {
    if (isMyCustomAction(action)) {
      console.log('Processing MyCustomAction with payload:', action.payload);
      // Custom logic for MyCustomAction
    }
    return next(action); // Pass all actions through
};

export default myCustomMiddleware;
This is a type-safe middleware in TypeScript that only processes actions of type 'MY_CUSTOM_ACTION'. It uses a type guard to perform a runtime check and enforce that the action is of the correct type before processing. All other actions are passed through unchanged.