Result<T, E>
Result
is used to represent computations that either succeed with a value (Ok<T>
) or fail with an error (Err<E>
).
1 2 3 4 5 6 7 |
|
Methods
map(fn: (value: T) => U): Result<U, E>
Maps over the Ok
value. Does nothing for Err
.
1 2 3 4 5 6 7 |
|
mapErr(fn: (err: E) => F): Result<T, F>
Maps over the Err
value. Does nothing for Ok
.
1 2 3 4 5 6 7 |
|
chain(fn: (value: T) => Result<U, E>): Result<U, E>
Chains the transformation if the value is Ok
. Returns Err
otherwise.
1 2 3 4 5 6 7 8 9 10 11 |
|
unwrapOr(defaultValue: T): T
Returns the value of Ok
, or the default value for Err
.
1 2 3 4 5 6 7 |
|
isOk(): boolean
Checks if the value is Ok
.
1 2 3 4 5 6 7 |
|
isErr(): boolean
Checks if the value is Err
.
1 2 3 4 5 6 7 |
|
match<T>(cases: { ok: (value: T) => T; err: (err: E) => T }): T
Matches the value to execute either the ok
or err
case.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
equals(other: Result<T, E>): boolean
Compares this
to another Result
, returns false
if the values inside are different.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Helpers
fromThrowable(fn, onError?)
Wraps a synchronous function in a Result
.
1 2 3 4 5 6 7 |
|
- Returns
Ok<T>
iffn()
succeeds - Returns
Err<E>
if it throws, usingonError
if provided
fromPromise(promise, onError?)
Wraps a Promise<T>
into a Promise<Result<T, E>>
.
1 2 3 4 5 |
|
- Resolves to
Ok<T>
on success - Resolves to
Err<E>
on failure
fromAsync(fn, onError?)
Same as fromPromise
, but lazy — receives a function returning a Promise.
1 2 3 4 5 |
|
- Allows deferred execution
- Handles exceptions from
async () => ...
Curried Helpers
mapR
Curried version of the map
function for Result
. This allows you to apply a transformation to the Ok value in a more functional style.
1 2 3 4 5 6 7 8 9 |
|
mapErrR
Curried version of mapErr
for Result
. This allows handling errors in a more functional composition style.
1 2 3 4 5 6 7 8 9 |
|
chainR
Curried version of chain
for Result
. This allows you to chain transformations on the Ok value in a functional pipeline.
1 2 3 4 5 6 7 8 9 |
|
unwrapOrR
Curried version of unwrapOr
for Result
. This provides a cleaner way to unwrap the value in a Result
, returning a default value if it's Err
.
1 2 3 4 5 6 7 8 |
|
matchR
Curried version of match
for Result
. This allows you to handle both Ok
and Err
in a functional way, providing a clean way to handle both cases.
1 2 3 4 5 6 7 8 9 10 11 |
|
equalsR
Curried version of equals
for Result
. Compares this
to another Result
, returns false
if the values inside are different.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|