← All Exercises

Discriminated Union Patterns

intermediatetypescript~20min

Background

Discriminated unions provide type-safe alternatives to enums with associated data, common in Redux-style reducers.

Problem

Define a discriminated union for counter actions (increment, decrement, set) and a reducer function with exhaustive type checking.

Input

An action from the discriminated union and a current state number.

Output

A new state number after applying the action.

Sample tests

Sample 1

Input: state=5, action={type:"increment"}
Expected: 6

Your solution

Learning objective

Master discriminated unions for type-safe state management with exhaustive pattern matching.