Overview
The “through” methods are similar to “tee” methods but with a key difference: they allow errors from the side operation to propagate. This is useful when you want to preserve the original value but need validation or persistence side effects that can fail.andThrough() - Sync Through Operations
Signature
Parameters
(t: T) => Result<unknown, F>
required
A function that receives the Ok value and returns a Result. The Ok value of the returned Result is ignored, but errors are propagated.
Returns
Returns aResult<T, E | F> where:
- If the original Result is
Ok(value)andf(value)returnsOk(_), returnsOk(value)(original value preserved) - If the original Result is
Ok(value)andf(value)returnsErr(error), returnsErr(error) - If the original Result is
Err(error), returnsErr(error)without callingf - Error types are accumulated as a union
asyncAndThrough() - Async Through Operations
Signature
Parameters
(t: T) => ResultAsync<unknown, F>
required
An async function that receives the Ok value and returns a ResultAsync. The Ok value of the returned ResultAsync is ignored, but errors are propagated.
Returns
Returns aResultAsync<T, E | F> that resolves to:
- If the original Result is
Ok(value)andf(value)resolves toOk(_), resolves toOk(value)(original value preserved) - If the original Result is
Ok(value)andf(value)resolves toErr(error), resolves toErr(error) - If the original Result is
Err(error), resolves toErr(error)without callingf
Examples
Basic andThrough Usage
Error Propagation
Validation with Preserved Value
Database Persistence
Async Database Validation
Multiple Validations
Real-World Example
Difference from andTee
Chaining Pattern
Implementation Details
andThrough for Ok (result.ts:341-346)
andThrough for Err (result.ts:439-441)
asyncAndThrough for Ok (result.ts:379-381)
asyncAndThrough for Err (result.ts:479-481)
Key Characteristics
- Value preservation: Original Ok value is passed through unchanged
- Error propagation: Errors from the through operation are propagated
- Type accumulation: Error types accumulate as union types
- Return value ignored: Only errors matter; Ok values from
fare discarded - Validation focus: Perfect for validations and side effects that can fail
Comparison: andTee vs andThrough
Use Cases
- Validation: Validate data while preserving the original object
- Persistence: Save to database but continue with the original data
- Conditional operations: Operations that may fail but shouldn’t transform the data
- Multi-step validation: Chain multiple validations while keeping the original value
- Side effects with errors: Unlike tee, errors actually matter
Related
- Result.andTee() - Side effects that never fail
- Result.andThen() - Chain with value transformation
- Result.map() - Transform Ok values