Use when working with data where exactly one option is active at a time - like operation results
that are either successful or failed, UI states that are loading, ready, or error, or any domain
model where alternatives are mutually exclusive.
The createRelay function lets you handle each option with a dedicated handler, while TypeScript
ensures all options are covered and values are accessed safely. Eliminates verbose conditional
logic and prevents bugs from unhandled options.
Type-safe relay for discriminated unions.
Use when working with data where exactly one option is active at a time - like operation results that are either successful or failed, UI states that are loading, ready, or error, or any domain model where alternatives are mutually exclusive.
The createRelay function lets you handle each option with a dedicated handler, while TypeScript ensures all options are covered and values are accessed safely. Eliminates verbose conditional logic and prevents bugs from unhandled options.
Basic Pattern Matching
Define options and match with function handlers:
Constant Handlers
Use constant values instead of functions when handlers don't need option data:
Partial Matching without Fallback
Handle specific options only, returning
undefinedfor unhandled options:Partial Matching with Fallback
Handle specific options and provide a fallback for others:
Delegation to Fallback
When a fallback is provided, handlers receive a delegate function to invoke common logic: