Blog>
Snippets

Integrating TypeScript with Redux middleware

Provide an example of a middleware written in TypeScript that uses the new typing system in Redux 5.0.0 to enhance type checking and IntelliSense in code editors.
import { Middleware, MiddlewareAPI, Dispatch, AnyAction } from 'redux';

// Defining a TypeScript interface for the state shape
interface MyState {
    // Define your state properties here
}

// Creating a logger middleware with the new Redux 5.0.0 typing
const loggerMiddleware: Middleware<{}, MyState> =
    (api: MiddlewareAPI<Dispatch<AnyAction>, MyState>) =>
    (next: Dispatch<AnyAction>) =>
    (action: AnyAction) => {
        // Output the state before the action
        console.log('State before:', api.getState());

        // Output the dispatched action
        console.log('Dispatching action:', action);

        // Call the next dispatch method in the middleware chain
        const result = next(action);

        // Output the state after the action
        console.log('State after:', api.getState());

        // This will likely be the action itself unless
        // a middleware further in chain changed it.
        return result;
    };

export default loggerMiddleware;
This code defines a logger middleware in TypeScript that conforms to the new typing system in Redux 5.0.0. It logs the state before and after an action is dispatched, as well as the action itself. It utilizes TypeScript interfaces and the Middleware type for enhanced type checking and better IntelliSense in code editors.