Blog>
Snippets

Typing Redux Action Creators

Provide examples of how to define type-safe action creators in TypeScript for use with Redux, ensuring that payloads and types are correctly used.
interface Action<Type extends string, Payload> {
  type: Type;
  payload: Payload;
}

function createAction<Type extends string, Payload>(type: Type, payload: Payload): Action<Type, Payload> {
  return { type, payload };
}
This TypeScript code defines a generic interface for an action with type and payload, and a function to create such an action. It ensures that the action type and payload are correctly typed.
type MyActionType = 'INCREMENT' | 'DECREMENT' | 'SET';

interface IncrementAction extends Action<'INCREMENT', undefined> {}
interface DecrementAction extends Action<'DECREMENT', undefined> {}
interface SetAction extends Action<'SET', number> {}
Defines specific action types and corresponding interfaces for the typing system with explicit action type and payload structure for increment, decrement, and set actions.
function increment(): IncrementAction {
  return createAction('INCREMENT', undefined);
}

function decrement(): DecrementAction {
  return createAction('DECREMENT', undefined);
}

function set(value: number): SetAction {
  return createAction('SET', value);
}
Provides three action creators for increment, decrement, and set actions that use the createAction function to ensure type safety.