CodShot
TypeScript Public

TypeScript Discriminated Union Reducer

Model reducer actions safely with exhaustive TypeScript checking.

#typescript #reducer #state #validation
TypeScript
type State = {
  count: number;
  label: string;
};

type Action =
  | {
      type: 'increment';
      amount: number;
    }
  | {
      type: 'rename';
      label: string;
    }
  | {
      type: 'reset';
    };

export function reducer(
  state: State,
  action: Action,
): State {
  switch (action.type) {
    case 'increment':
      return {
        ...state,
        count: state.count + action.amount,
      };

    case 'rename':
      return {
        ...state,
        label: action.label,
      };

    case 'reset':
      return {
        count: 0,
        label: '',
      };

    default: {
      const exhaustiveCheck: never = action;
      return exhaustiveCheck;
    }
  }
}

Snippet actions

CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0
Forks
CodShot AI Help
Ask about CodShot features, plans, workspace, AI limits, referrals, and public help topics.
Hi! I can help you understand how CodShot works. What would you like to know?
For account-specific or sensitive issues, please open a support ticket. Open support