Skip to main content

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)

Call match() as a method on the Result instance:
Data-first is more concise for one-off transformations.

Data-Last (Pipeable Style)

Pass handlers first, Result last - enables composition:
Data-last is useful for creating reusable transformations and pipelines.

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

Nested match() calls can become verbose. Consider using andThen() or Result.gen() for cleaner composition.

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

When you need different logic for success vs error:
When you want to handle errors first:
When you just need a default value:
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