Blog>
Snippets

Advanced TypeScript typing for Redux middleware

Example of how to create custom middleware with complex typings, using advanced TypeScript features to ensure type safety in Redux 5.0.0.
import { Middleware, Dispatch, AnyAction } from 'redux';

// Define a state type for your app
interface MyState {
  // Your state properties here
}

// Define custom Action types if needed
interface MyAction extends AnyAction {
  // Your action properties here
}

// Define a custom middleware type using generics for State and Action
type MyMiddleware<TState = MyState, TAction = MyAction> = Middleware<{}, TState, Dispatch<TAction>>;

// Create a middleware with complex type safety
const myCustomMiddleware: MyMiddleware = storeApi => next => action => {
  // Your middleware logic here
  // You can access state with: storeApi.getState()
  // And dispatch actions with: storeApi.dispatch(action)

  // Pass the action to next middleware or reducer
  return next(action);
};

export default myCustomMiddleware;
This piece of code is an example of a custom middleware for Redux with advanced TypeScript typings. The interface 'MyState' is where you define the structure of the application's state. 'MyAction' extends 'AnyAction' from Redux to include any custom properties needed for the actions in your app. 'MyMiddleware' is a type that uses generics to define the Middleware with the correct State and Action types. The middleware itself, 'myCustomMiddleware', is then typed with 'MyMiddleware' and provides type-safe access to the state and dispatch methods inside its logic. Lastly, the middleware is exported for use in the Redux store.