Skip to main content

Function: andThen()

andThen<T, U, E>(result, fn): Result<U, E>

Defined in: src/types/result.ts:327

Chains a function that returns a Result over a Result (flatMap).

Type Parameters​

• T

Original success value type

• U

New success value type

• E extends Error

Error type

Parameters​

result​

Result<T, E>

Result to chain over

fn​

(value) => Result<U, E>

Function returning a new Result

Returns​

Result<U, E>

Flattened Result

Remarks​

If the Result is Ok, applies the function to the value. If the Result is Err, returns the error unchanged.

Use this to chain multiple fallible operations without nesting Results.

Example​

function divide(a: number, b: number): Result<number, Error> {
return b === 0 ? Err(new Error('Division by zero')) : Ok(a / b);
}

const result = Ok(10);
const chained = andThen(result, (x) => divide(x, 2));
// Ok(5)