Blog>
Snippets

Migrating Middleware to TypeScript

Demonstrate how to update a Redux middleware function to enforce action type safety using TypeScript's type declarations.
import { Middleware } from 'redux';

// Define a custom action type
interface CustomAction {
  type: 'CUSTOM_ACTION';
  payload: string;
}

// Other action types can be defined similarly
// ... (other action interfaces)

// Union action type for the middleware to handle
type ActionTypes = CustomAction; // | OtherAction | AnotherAction;

// Middleware to log actions
export const loggerMiddleware: Middleware<{}, any, Dispatch<ActionTypes>> = storeApi => next => action => {
  console.log('dispatching', action);
  let result = next(action);
  console.log('next state', storeApi.getState());
  return result;
};
This code creates a middleware function using TypeScript that logs actions and states. We define a custom action interface, 'CustomAction', and a union type, 'ActionTypes', that our middleware will handle. The 'loggerMiddleware' uses the 'Middleware' type from Redux, properly typed with 'ActionTypes'.