Course contentsShow
← TypeScript
Lesson 425 of 1,7969. Union TypesFree lesson

Exhaustiveness in Functional Patterns

Using exhaustive matching in reducer functions, pattern-matching libraries, or expression-based handlers.

Exhaustiveness in Functional Patterns

What you'll learn: How to apply exhaustive matching principles to reducers, pattern-matching libraries, and expression-based handlers for compile-time safety.

The Pattern in Functional Code

You've seen exhaustiveness checking in switch statements with discriminated unions. But TypeScript's type system can guarantee completeness in many functional programming patterns too — anywhere you handle all variants of a union type.

The key insight: any expression that processes union variants can benefit from the never type to ensure you've handled every case.

Reducers and Expression Bodies

In reducer functions (like Redux or useReducer), you can structure your code to leverage exhaustiveness:

type Action = 
  | { type: 'increment' }
  | { type: 'decrement' }
  | { type: 'reset', value: number };

function reducer(state: number, action: Action): number {
  switch (action.type) {
    case 'increment': return state + 1;
    case 'decrement': return state - 1;
    case 'reset': return action.value;
    default: {
      const _exhaustive: never = action;
      return _exhaustive;
    }
  }
}

You can also use expression-based patterns with ternary operators or immediately-invoked functions when handling simpler unions.

Helper Functions for Handlers

Create handler objects where each union variant maps to a function:

type Result = { status: 'success', data: string } | { status: 'error', message: string };

const handlers = {
  success: (r: Extract<Result, { status: 'success' }>) => r.data,
  error: (r: Extract<Result, { status: 'error' }>) => r.message
};

function handle(result: Result): string {
  return handlers[result.status](result as any);
}

Key Takeaway: Exhaustiveness checking isn't limited to switch statements — apply it to any functional pattern (reducers, handlers, matchers) to guarantee all union variants are processed at compile time.