Blog>
Snippets

Creating Typed Redux Action Creators

Illustrate the creation of strongly-typed Redux action creators as a replacement for those using AnyAction.
// Define the types for our action creators
interface IncrementAction {
  type: 'INCREMENT',
  payload: number
}

interface DecrementAction {
  type: 'DECREMENT',
  payload: number
}

// Union type for our actions
type CounterAction = IncrementAction | DecrementAction;

// Action Creators
const increment = (amount: number): IncrementAction => ({
  type: 'INCREMENT',
  payload: amount
});

const decrement = (amount: number): DecrementAction => ({
  type: 'DECREMENT',
  payload: amount
});
This code snippet defines two action creator functions, `increment` and `decrement`, for a Redux counter application. The functions return actions with types `INCREMENT` and `DECREMENT`, respectively, and a payload containing the change amount. TypeScript interfaces are used to ensure the actions conform to the correct structure, enforcing type safety.