Overview
Pattern matching in better-result allows you to handle both success and error cases in a type-safe way:- Result.match() - Exhaustive matching with ok/err handlers
- isOk() / isErr() - Type guards for narrowing
- Data-first and data-last APIs - Flexible composition styles
Result.match()
Exhaustively handle both success and error cases by providing handlers for each variant.Basic Usage
Type Signature
Real-World Example
Data-First vs Data-Last
better-result supports both API styles for maximum flexibility.Data-First (Method Style)
Callmatch() as a method on the Result instance:
Data-Last (Pipeable Style)
Pass handlers first, Result last - enables composition:Pipeable Composition
Combine multiple transformations:Type Narrowing with isOk/isErr
Use type guards to narrow the Result type before accessing properties.isOk() Type Guard
isErr() Type Guard
Negation Type Narrowing
Negated guards also narrow the type:Static Type Guards
Use static functions from the Result namespace:Result.isOk()
Result.isError()
Result.isError() (with an “r”) matches the Err status field which is "error" (also with an “r”).Exhaustive Matching Patterns
Converting to HTTP Response
Async Operations
Early Return Pattern
The early return pattern works well for imperative code. For functional composition, use
andThen() or Result.gen() instead.Combining Pattern Matching
Nested Results
Flattened with andThen
Same logic, cleaner:Error Handler Patterns
Logging Errors
Converting Errors to Metrics
Fallback Values
Type Inference
TypeScript infers return types from your handlers:Best Practices
Use match() for branching logic
Use match() for branching logic
When you need different logic for success vs error:
Use isOk/isErr for early returns
Use isOk/isErr for early returns
When you want to handle errors first:
Use unwrapOr for simple fallbacks
Use unwrapOr for simple fallbacks
When you just need a default value:
Prefer andThen over nested match
Prefer andThen over nested match
For sequential operations:
Real-World Example
Complete user registration flow:Next Steps
Generator Composition
Learn Result.gen() for imperative-style error handling
Error Handling
Master TaggedError and exhaustive error matching