Blog>
Snippets

Enforcing action payload types

Show how to enforce types for action payloads within middleware to ensure that only valid data progresses through the Redux flow.
// Middleware for enforcing action payload types
const enforcePayloadTypeMiddleware = (store) => (next) => (action) => {
  // Define the expected types for each action type
  const actionPayloadTypes = {
    'ADD_TODO': 'string',
    'SET_VISIBILITY_FILTER': 'string',
    'TOGGLE_TODO': 'number'
  };

  // Check if action type requires type enforcement
  if (action.type in actionPayloadTypes) {
    const expectedType = actionPayloadTypes[action.type];
    // Validate payload type
    if (typeof action.payload !== expectedType) {
      throw new Error(`Invalid payload type for action ${action.type}: expected ${expectedType}, got ${typeof action.payload}`);
    }
  }

  // If payload is valid, or action doesn't need enforcement, pass the action to the next middleware or reducer
  return next(action);
};
This JavaScript code defines a Redux middleware function that checks the type of the action payload against a predefined set of action types and their corresponding expected payload types. If the payload doesn't match the expected type, it throws an error. Otherwise, it forwards the action to the next middleware or reducer.