Skip to main content

Overview

Similar to map, but the mapping function must return a new Result. This is useful for chaining computations where each step might fail, and is excellent for flattening nested Results.

Signature

Parameters

(t: T) => Result<U, F>
required
A function that takes the Ok value and returns a new Result. This function is only called if the current Result is Ok.

Returns

Returns a new Result<U, E | F> where:
  • If the original Result is Ok(value), returns the result of f(value)
  • If the original Result is Err(error), returns Err(error) without calling f
  • Error types from both Results are combined as a union type

Examples

Basic Chaining

Flattening Nested Results

Sequential Operations

Distinct Error Types (v4.1.0+)

Real-World Example

Error Short-Circuiting

Implementation Details

From the source code (result.ts:337-339):
For Err (result.ts:461-463):

Notes

  • andThen is also known as flatMap or bind in other functional programming libraries
  • Perfect for avoiding nested Results like Result<Result<T, E2>, E1>
  • All error types are preserved as a union type
  • For async operations, use asyncAndThen()
  • The operation short-circuits on the first error