Overview
Maps aResult<T, E> to Result<T, F> by applying a function to a contained Err value, leaving an Ok value untouched. This is useful for transforming error values, such as converting low-level errors to user-friendly messages.
Signature
Parameters
(e: E) => U
required
A function that transforms the Err value from type
E to type U. This function is only called if the Result is Err.Returns
Returns a newResult<T, U> where:
- If the original Result is
Ok(value), returnsOk(value)unchanged - If the original Result is
Err(error), returnsErr(f(error))
Examples
Basic Error Transformation
Skips Ok Values
Convert Low-Level Errors
Error Type Conversion
Chaining Error Transformations
Real-World HTTP Example
Implementation Details
From the source code (result.ts:435-437):Ok (result.ts:328-330):
Notes
- The mapping function is only executed for
Errvalues - The success type
Tremains unchanged - This method does not catch exceptions thrown by the mapping function
- Useful for error normalization across different layers of your application
- Can be combined with
.map()to transform both success and error paths
Related
- Result.map() - Transform success values
- Result.orElse() - Recover from errors with a Result
- Result.match() - Handle both Ok and Err cases