Course contentsShow
← TypeScript
Lesson 849 of 1,79619. Template Literal TypesFree lesson

Type-Safe Action Creators

Generate Redux-style action creator types from action names using mapped types and template literals.

Type-Safe Action Creators

What you'll learn: How to use mapped types and template literals to automatically generate fully-typed Redux action creator types from action names.

The Action Creator Problem

In Redux-style architectures, you typically have action types (string constants) and action creator functions that build those actions. Manually typing each creator is repetitive and error-prone:

type LoginAction = { type: 'user/login'; payload: string };
type LogoutAction = { type: 'user/logout' };
type FetchDataAction = { type: 'data/fetch'; payload: number };

// Manually typing each creator
type LoginCreator = (payload: string) => LoginAction;
type LogoutCreator = () => LogoutAction;
type FetchCreator = (payload: number) => FetchDataAction;

Generating Creators from Action Names

By combining mapped types and template literal types, you can generate all action creator types at once:

type ActionMap = {
  'user/login': string;
  'user/logout': never;
  'data/fetch': number;
};

type ActionCreators<M> = {
  [K in keyof M]: M[K] extends never
    ? () => { type: K }
    : (payload: M[K]) => { type: K; payload: M[K] }
};

type Creators = ActionCreators<ActionMap>;
// Creators = {
//   'user/login': (payload: string) => { type: 'user/login'; payload: string };
//   'user/logout': () => { type: 'user/logout' };
//   'data/fetch': (payload: number) => { type: 'data/fetch'; payload: number };
// }

The mapped type iterates over each action name, checking whether it requires a payload (never means no payload).

Why This Matters

This pattern ensures your action creators stay perfectly synchronized with your action definitions. Change the payload type once in ActionMap, and all creators update automatically. It's a single source of truth that prevents mismatches between action types and their creators.

Key Takeaway: Mapped types with conditional logic can transform a simple action name → payload type mapping into a complete, type-safe set of action creator signatures, eliminating boilerplate and preventing inconsistencies.