Class: Ok<T, E>
Defined in: src/ok.ts:8
Successful variant of Result.
See
Err - for the error variant
Example
const result = Result.ok(42)
result.isOk() // => true
result.unwrap() // => Ok(42)Type Parameters
| Type Parameter | Default type | Description |
|---|---|---|
T | - | Type of the success value |
E | never | Error type carried by Result. Present only for union compatibility |
Implements
Ok<T,E>
Type Guards
isErr()
isErr():
this is Err<T, E>
Defined in: src/ok.ts:22
Returns true when this result is the Err variant.
Returns
this is Err<T, E>
See
isOk - Opposite check.
Example
Result.err('failed').isErr() // => true
Result.ok(42).isErr() // => falseImplementation of
isErrAnd()
isErrAnd(
_condition):this is Err<T, E>
Defined in: src/ok.ts:30
Returns true when this result is Err and its error satisfies the provided predicate.
Parameters
| Parameter | Type |
|---|---|
_condition | (error) => boolean |
Returns
this is Err<T, E>
See
isOkAnd - Opposite check for success values.
Example
Result.err('timeout').isErrAnd((e) => e === 'timeout') // => true
Result.ok(42).isErrAnd(() => true) // => falseImplementation of
isOk()
isOk():
this is Ok<T, E>
Defined in: src/ok.ts:18
Returns true when this result is the Ok variant.
Returns
this is Ok<T, E>
See
isErr - Opposite check.
Example
Result.ok(42).isOk() // => true
Result.err('failed').isOk() // => falseImplementation of
isOkAnd()
isOkAnd(
condition):this is Ok<T, E>
Defined in: src/ok.ts:26
Returns true when this result is Ok and its value satisfies the provided predicate.
Parameters
| Parameter | Type | Description |
|---|---|---|
condition | (value) => boolean | Predicate used to validate the success value. |
Returns
this is Ok<T, E>
See
isErrAnd - Opposite check for errors.
Example
Result.ok(42).isOkAnd((x) => x > 40) // => true
Result.ok(10).isOkAnd((x) => x > 40) // => false
Result.err('fail').isOkAnd(() => true) // => falseImplementation of
Alternation
and()
and<
U,E2>(other):Result<U,E|E2>
Defined in: src/ok.ts:109
Returns other when this result is Ok.
If this result is Err, the current error is preserved.
Commonly used to sequence results while discarding the current success value.
Type Parameters
| Type Parameter | Default type | Description |
|---|---|---|
U | - | Next success value type. |
E2 | never | Next error type. |
Parameters
| Parameter | Type | Description |
|---|---|---|
other | Result<U, E2> | Result returned when this result is Ok. |
Returns
Result<U, E | E2>
See
Example
Result.ok(1).and(Result.ok(2)) // => Ok(2)
Result.ok(1).and(Result.err('fail')) // => Err("fail")
Result.err('fail').and(Result.ok(42)) // => Err("fail")Implementation of
andThen()
andThen<
U,E2>(next):Result<U,E|E2>
Defined in: src/ok.ts:113
Chains a function that returns another Result.
If this result is Ok, next receives the success value. If this result is Err, the current error is preserved.
Also known as flatMap or bind.
Type Parameters
| Type Parameter | Default type | Description |
|---|---|---|
U | - | Next success value type. |
E2 | never | Next error type. |
Parameters
| Parameter | Type | Description |
|---|---|---|
next | (value) => Result<U, E2> | Function that returns the next result. |
Returns
Result<U, E | E2>
See
- andThenAsync - Async version.
- map - Transform without flattening.
Example
Result.ok(5).andThen((x) => Result.ok(x * 2))
// => Ok(10)
Result.ok(5).andThen(() => Result.err('failure'))
// => Err("failure")
Result.err('fail').andThen((x) => Result.ok(x * 2))
// => Err("fail")Implementation of
or()
or<
U,E2>(_other):Result<T|U,E2>
Defined in: src/ok.ts:117
Returns this result when it is Ok, otherwise returns other.
Commonly used to provide a fallback result.
Type Parameters
| Type Parameter | Default type | Description |
|---|---|---|
U | T | Alternative success type |
E2 | never | Alternative error type |
Parameters
| Parameter | Type |
|---|---|
_other | Result<U, E2> |
Returns
Result<T | U, E2>
See
Example
Result.ok(1).or(Result.ok(2)) // => Ok(1)
Result.err('fail').or(Result.ok(42)) // => Ok(42)Implementation of
orElse()
orElse<
U,E2>(_fallback):Result<T|U,E2>
Defined in: src/ok.ts:121
Returns this result when it is Ok, otherwise invokes fallback with the current error.
Useful for recovery flows that depend on the failure reason.
Type Parameters
| Type Parameter | Default type | Description |
|---|---|---|
U | T | Recovery success type |
E2 | never | Recovery error type |
Parameters
| Parameter | Type |
|---|---|
_fallback | (error) => Result<U, E2> |
Returns
Result<T | U, E2>
See
- orElseAsync - Async version.
- or - Use a static fallback result.
Example
Result.ok(42).orElse(() => Result.ok(0))
// => Ok(42)
Result.err('not found').orElse(() => Result.ok(null))
// => Ok(null)
Result.err('fail').orElse(() => Result.err('backup'))
// => Err("backup")Implementation of
Async Alternation
andAsync()
andAsync<
U,E2>(other):AsyncResult<U,E|E2>
Defined in: src/ok.ts:209
Returns other when this result is Ok.
If this result is Err, the current error is preserved.
Type Parameters
| Type Parameter | Default type | Description |
|---|---|---|
U | - | Next success value type. |
E2 | never | Next error type. |
Parameters
| Parameter | Type | Description |
|---|---|---|
other | AsyncResult<U, E2> | Async result returned when this result is Ok. |
Returns
AsyncResult<U, E | E2>
See
and - Sync version
Example
await Result.ok(5).andAsync(
Promise.resolve(Result.ok(10))
)
// => Ok(10)
await Result.err('fail').andAsync(
Promise.resolve(Result.ok(42))
)
// => Err("fail")Implementation of
andThenAsync()
andThenAsync<
U,E2>(next):AsyncResult<U,E|E2>
Defined in: src/ok.ts:213
Chains an asynchronous function that returns another Result.
If this result is Ok, next receives the success value. If this result is Err, the current error is preserved.
Type Parameters
| Type Parameter | Default type | Description |
|---|---|---|
U | - | Next success value type. |
E2 | never | Next error type. |
Parameters
| Parameter | Type | Description |
|---|---|---|
next | (value) => AsyncResult<U, E2> | Async function that returns the next result. |
Returns
AsyncResult<U, E | E2>
See
andThen - Sync version
Example
await Result.ok(userId).andThenAsync(async (id) => {
const user = await fetchUser(id)
return user ? Result.ok(user) : Result.err('not found')
})
await Result.err('fail').andThenAsync(
async (x) => Result.ok(x * 2)
)
// => Err("fail")Implementation of
orAsync()
orAsync<
U,E2>(_other):AsyncResult<T|U,E2>
Defined in: src/ok.ts:217
Returns this result when it is Ok, otherwise returns other.
Type Parameters
| Type Parameter | Default type | Description |
|---|---|---|
U | T | Alternative success value type. |
E2 | never | Alternative error type. |
Parameters
| Parameter | Type |
|---|---|
_other | AsyncResult<U, E2> |
Returns
AsyncResult<T | U, E2>
See
or - Sync version
Example
await Result.ok(5).orAsync(
Promise.resolve(Result.ok(10))
)
// => Ok(5)
await Result.err('fail').orAsync(
Promise.resolve(Result.ok(42))
)
// => Ok(42)Implementation of
orElseAsync()
orElseAsync<
U,E2>(_fallback):AsyncResult<T|U,E2>
Defined in: src/ok.ts:221
Returns this result when it is Ok, otherwise invokes fallback asynchronously with the current error.
Useful for async recovery flows that depend on the failure reason.
Type Parameters
| Type Parameter | Default type | Description |
|---|---|---|
U | T | Recovery success value type. |
E2 | never | Recovery error type. |
Parameters
| Parameter | Type |
|---|---|
_fallback | (error) => AsyncResult<U, E2> |
Returns
AsyncResult<T | U, E2>
See
orElse - sync version
Example
await Result.ok(5).orElseAsync(
async () => Result.ok(0)
)
// => Ok(5)
await Result.err('not found').orElseAsync(
async () => Result.ok(42)
)
// => Ok(42)Implementation of
Async Transformation
mapAsync()
mapAsync<
U>(mapper):AsyncResult<U,E>
Defined in: src/ok.ts:186
Asynchronously transforms the success value.
If this result is Err, the original error is preserved.
Type Parameters
| Type Parameter | Description |
|---|---|
U | Mapped success value type. |
Parameters
| Parameter | Type | Description |
|---|---|---|
mapper | (value) => Promise<U> | Async function applied to the success value. |
Returns
AsyncResult<U, E>
See
map - sync version
Example
await Result.ok(1).mapAsync(async (x) => x + 1)
// => Ok(2)
await Result.err('fail').mapAsync(async (x) => x + 1)
// => Err('fail')Implementation of
mapErrAsync()
mapErrAsync<
E2>(_mapper):AsyncResult<T,E2>
Defined in: src/ok.ts:190
Asynchronously transforms the error value.
If this result is Ok, the original success value is preserved.
Type Parameters
| Type Parameter | Description |
|---|---|
E2 | Mapped error type. |
Parameters
| Parameter | Type |
|---|---|
_mapper | (error) => Promise<E2> |
Returns
AsyncResult<T, E2>
See
mapErr - Sync version
Example
await Result.ok(5).mapErrAsync(async (e) => e + 1)
// => Ok(5)
await Result.err('fail').mapErrAsync(
async (e) => new Error(e)
)
// => Err(Error: "fail")Implementation of
mapOrAsync()
mapOrAsync<
U>(mapper,_defaultValue):Promise<U>
Defined in: src/ok.ts:194
Asynchronously maps the success value or returns the provided fallback when this result is Err.
Type Parameters
| Type Parameter | Description |
|---|---|
U | Return type. |
Parameters
| Parameter | Type | Description |
|---|---|---|
mapper | (value) => Promise<U> | Async function applied to the success value. |
_defaultValue | U | - |
Returns
Promise<U>
See
mapOr - Sync version
Example
await Result.ok(5).mapOrAsync(async (x) => x * 2, 0)
// => 10
await Result.err('fail').mapOrAsync(async (x) => x * 2, 0)
// => 0Implementation of
mapOrElseAsync()
mapOrElseAsync<
U>(okMapper,_errMapper):Promise<U>
Defined in: src/ok.ts:198
Asynchronously maps either branch of the result into a shared output type.
Uses okMapper for Ok and errMapper for Err.
Type Parameters
| Type Parameter | Description |
|---|---|
U | Result type |
Parameters
| Parameter | Type | Description |
|---|---|---|
okMapper | (value) => Promise<U> | Async function applied to the success value. |
_errMapper | (error) => Promise<U> | - |
Returns
Promise<U>
See
mapOrElse - Sync version
Example
await Result.ok(5).mapOrElseAsync(
async (x) => x * 2,
async () => -1
)
// => 10
await Result.err('fail').mapOrElseAsync(
async (x) => x * 2,
async () => -1
)
// => -1Implementation of
Combination
zip()
zip<
U,E2>(other):Result<[T,U],E|E2>
Defined in: src/ok.ts:129
Combines this result with another result into a tuple.
Returns Ok only when both results are successful. If either result is Err, the first encountered error is returned.
Type Parameters
| Type Parameter | Description |
|---|---|
U | Second success type |
E2 | Second error type |
Parameters
| Parameter | Type | Description |
|---|---|---|
other | Result<U, E2> | Result to combine with this one. |
Returns
Result<[T, U], E | E2>
See
zipWith - Combine and map in one step.
Example
Result.ok(1).zip(Result.ok('a')) // => Ok([1, 'a'])
Result.ok(1).zip(Result.err('b')) // => Err('b')Implementation of
zipWith()
zipWith<
U,R,E2>(other,combine):Result<R,E|E2>
Defined in: src/ok.ts:137
Combines two successful results and maps their values.
Returns Ok only when both results are successful. If either result is Err, the first encountered error is returned.
Type Parameters
| Type Parameter | Description |
|---|---|
U | Second success value type. |
R | Combined return type. |
E2 | Second error type. |
Parameters
| Parameter | Type | Description |
|---|---|---|
other | Result<U, E2> | Second result. |
combine | (value, otherValue) => R | Function applied to both success values. |
Returns
Result<R, E | E2>
See
zip - Return a tuple instead of mapping.
Example
Result.ok(2).zipWith(
Result.ok(3),
(a, b) => a + b
) // => Ok(5)
Result.ok('hello').zipWith(
Result.ok('world'),
(a, b) => `${a} ${b}`,
) // => Ok("hello world")
Result.ok(2).zipWith(
Result.err('fail'),
(a, b) => a + b,
) // => Err("fail")Implementation of
Constructors
Constructor
new Ok<
T,E>(value):Ok<T,E>
Defined in: src/ok.ts:12
Parameters
| Parameter | Type |
|---|---|
value | T |
Returns
Ok<T, E>
Conversion
toJSON()
toJSON():
object
Defined in: src/ok.ts:235
Converts this result into a plain JSON-serializable object.
Returns
object
| Name | Type | Defined in |
|---|---|---|
type | "ok" | src/ok.ts:235 |
value | T | src/ok.ts:235 |
Example
Result.ok(42).toJSON()
// { type: 'ok', value: 42 }
Result.err('fail').toJSON()
// { type: 'err', error: 'fail' }Implementation of
toNullable()
toNullable():
T
Defined in: src/ok.ts:239
Converts this result into a nullable value.
Returns the success value when this result is Ok, otherwise returns null.
Returns
T
See
toValue - Return undefined on error instead.
Example
Result.ok(42).toNullable() // => 42
Result.err('failed').toNullable() // => nullImplementation of
toString()
toString():
string
Defined in: src/ok.ts:231
Returns a string representation of this result.
Formats the current value as Ok(value) or Err(error).
Returns
string
Example
Result.ok(42).toString() // => "Ok(42)"
Result.err('fail').toString() // => "Err("fail")"Implementation of
toValue()
toValue():
T
Defined in: src/ok.ts:243
Converts this result into an optional value.
Returns the success value when this result is Ok, otherwise returns undefined.
Returns
T
See
toNullable - Return null on error instead.
Example
Result.ok(42).toValue() // => 42
Result.err('failed').toValue() // => undefinedImplementation of
Extraction
expect()
expect(
_reason):T
Defined in: src/ok.ts:54
Returns the success value.
Parameters
| Parameter | Type |
|---|---|
_reason | string |
Returns
T
See
Throws
- With
reasonand the original error ascause.
Examples
Result.ok(42).expect('should exist')
// => 42Result.err('failed').expect('should exist')
// => throws Error("should exist", { cause: "failed" })Implementation of
expectErr()
expectErr(
reason):never
Defined in: src/ok.ts:58
Returns the error value.
Throws with the provided message if this result is Ok.
Parameters
| Parameter | Type | Description |
|---|---|---|
reason | string | Custom error message. |
Returns
never
See
Throws
- With
reasonand the original value ascause.
Examples
Result.err('fail').expectErr('should be error')
// => 'fail'Result.ok(42).expectErr('should be error')
// => throws Error("should be error", { cause: 42 })Implementation of
unwrap()
unwrap():
T
Defined in: src/ok.ts:38
Returns the contained success value.
Throws if this result is Err.
Returns
T
See
Throws
- If called on an Err result.
Examples
Result.ok(42).unwrap() // => 42Result.err('fail').unwrap()
// => throws Error("Called unwrap on an Err value", { cause: "fail" })if (result.isOk()) {
result.unwrap() // safe
}Implementation of
unwrapErr()
unwrapErr():
never
Defined in: src/ok.ts:42
Returns the contained error value.
Throws if this result is Ok.
Returns
never
See
unwrap - Extract the success value.
Throws
- If called on an Ok result.
Examples
Result.err('failed').unwrapErr()
// => "failed"Result.ok(42).unwrapErr()
// => throws Error("Called unwrapErr on an Ok value", { cause: 42 })if (result.isErr()) {
result.unwrapErr() // safe
}Implementation of
unwrapOr()
unwrapOr<
U>(_defaultValue):T|U
Defined in: src/ok.ts:46
Returns the success value, or the provided fallback when this result is Err.
Type Parameters
| Type Parameter | Default type |
|---|---|
U | T |
Parameters
| Parameter | Type |
|---|---|
_defaultValue | U |
Returns
T | U
See
- unwrap - Throw on failure.
- unwrapOrElse - Compute a fallback lazily.
Example
Result.ok(42).unwrapOr(0) // => 42
Result.err('failed').unwrapOr(0) // => 0Implementation of
unwrapOrElse()
unwrapOrElse<
U>(_fallback):T|U
Defined in: src/ok.ts:50
Returns the success value, or computes a fallback from the error when this result is Err.
Type Parameters
| Type Parameter | Default type |
|---|---|
U | T |
Parameters
| Parameter | Type |
|---|---|
_fallback | (error) => U |
Returns
T | U
See
unwrapOr - Use a static fallback value.
Example
Result.ok(42).unwrapOrElse((e) => e.length) // => 42
Result.err('failed').unwrapOrElse((e) => e.length) // => 6Implementation of
Inspection
contains()
contains<
U>(value,comparator?):boolean
Defined in: src/ok.ts:152
Returns true when this result is Ok and its value is strictly equal to value.
Uses === comparison.
Type Parameters
| Type Parameter | Description |
|---|---|
U | Comparable value type. |
Parameters
| Parameter | Type | Description |
|---|---|---|
value | U | Expected value. |
comparator? | (actual, expected) => boolean | - |
Returns
boolean
Example
Result.ok(42).contains(42) // => true
Result.ok({ id: 42 }).contains({ id: 42 }) // => true
Result.ok(42).contains(99) // => false
Result.err('fail').contains(42) // => falseImplementation of
inspect()
inspect(
action):this
Defined in: src/ok.ts:172
Runs a callback when this result is Ok.
Intended for side effects such as logging, metrics, or debugging. Returns the original result for chaining.
Parameters
| Parameter | Type | Description |
|---|---|---|
action | (value) => void | Callback invoked with the success value. |
Returns
this
See
- inspectErr - Side effects for errors.
- match - Branch on both states.
Example
Result.ok(42).inspect((value) => console.log(value))
// => logs 42, returns Ok(42)Implementation of
inspectErr()
inspectErr(
_action):this
Defined in: src/ok.ts:178
Runs a callback when this result is Err.
Intended for side effects such as logging, metrics, or debugging. Returns the original result for chaining.
Parameters
| Parameter | Type |
|---|---|
_action | (error) => void |
Returns
this
See
inspect - Side effects for success values.
Example
Result.err('fail').inspectErr(e => console.log(e))
// => logs "fail", returns Err("fail")Implementation of
match()
match<
L,R>(cases):L|R
Defined in: src/ok.ts:168
Pattern matches the current result.
Executes cases.ok for Ok or cases.err for Err, returning the selected branch result.
Type Parameters
| Type Parameter | Description |
|---|---|
L | Return type for the success branch. |
R | Return type for the error branch. |
Parameters
| Parameter | Type | Description |
|---|---|---|
cases | MatchCases<T, E, L, R> | Branch handlers. |
Returns
L | R
See
- inspect - Run side effects for success values.
- inspectErr - Run side effects for errors.
Examples
Result.ok(5).match({
ok: (x) => `Success: ${x * 2}`,
err: (e) => `Error: ${e}`
})
// => "Success: 10"Result.err('not found').match({
ok: (x) => `Value: ${x}`,
err: (e) => `Error: ${e}`
})
// => "Error: not found"Implementation of
Transformation
filter()
filter(
condition,reason?):Result<T,Error>
Defined in: src/ok.ts:82
Validates the success value with a predicate.
If this result is Ok and the predicate returns false, converts it to Err.
Existing Err values are preserved.
Parameters
| Parameter | Type | Description |
|---|---|---|
condition | (value) => boolean | Predicate used to validate the success value. |
reason? | string | Optional custom error message. |
Returns
Result<T, Error>
See
- isOkAnd - Validate without transforming.
- filterOrElse - Provide a custom error value.
Example
Result.ok(42).filter((x) => x > 10)
// => Ok(42)
Result.ok(42).filter((x) => x > 50, 'Too small')
// => Err(Error: "Too small", { cause: 42 })Implementation of
filterOrElse()
filterOrElse<
E2>(condition,onFailure):Result<T,E|E2>
Defined in: src/ok.ts:90
Validates the success value with a predicate.
If validation fails, converts the result to Err using the provided error factory.
Existing Err values are preserved.
Type Parameters
| Type Parameter | Description |
|---|---|
E2 | Additional error type. |
Parameters
| Parameter | Type | Description |
|---|---|---|
condition | (value) => boolean | Predicate used to validate the success value. |
onFailure | (value) => E2 | Function used to create the failure value. |
Returns
Result<T, E | E2>
See
filter - Use a default error message.
Example
Result.ok(42).filterOrElse(
(x) => x > 10,
(x) => new Error('Too small')
) // => Ok(42)
Result.ok(42).filterOrElse(
(x) => x > 50,
(x) => new Error('Too small')
) // => Err(Error: "Too small", { cause: 42 })Implementation of
flatten()
flatten<
U,E2>(this):Result<U,E|E2>
Defined in: src/ok.ts:101
Flattens a nested Result.
Converts Result<Result<U, E2>, TError> into Result<U, TError | E2>.
Type Parameters
| Type Parameter | Description |
|---|---|
U | Inner success value type. |
E2 | Inner error type. |
Parameters
| Parameter | Type |
|---|---|
this | Ok<Result<U, E2>, E> |
Returns
Result<U, E | E2>
Example
Result.ok(Result.ok(42)).flatten() // => Ok(42)
Result.ok(Result.err('fail')).flatten() // => Err("fail")
Result.err('outer').flatten() // Err("outer")Implementation of
map()
map<
U>(mapper):Result<U,E>
Defined in: src/ok.ts:66
Transforms the success value using the provided mapper.
If this result is Err, the original error is preserved.
Type Parameters
| Type Parameter | Description |
|---|---|
U | Mapped success value type. |
Parameters
| Parameter | Type | Description |
|---|---|---|
mapper | (value) => U | Function applied to the success value. |
Returns
Result<U, E>
See
- mapAsync - Async version.
- mapOr - Return a fallback value on error.
- mapErr - Transform the error value instead.
Example
Result.ok(42).map((x) => x * 2) // => Ok(84)
Result.err('fail').map((x) => x * 2) // => Err("fail")Implementation of
mapErr()
mapErr<
E2>(_mapper):Result<T,E2>
Defined in: src/ok.ts:78
Transforms the error value using the provided mapper.
If this result is Ok, the original success value is preserved.
Type Parameters
| Type Parameter | Description |
|---|---|
E2 | Mapped error type. |
Parameters
| Parameter | Type |
|---|---|
_mapper | (error) => E2 |
Returns
Result<T, E2>
See
mapErrAsync - Async version.
Example
Result.err('not found').mapErr((e) => new Error(e))
// => Err(Error: "not found")
Result.ok(42).mapErr((e) => new Error(String(e)))
// => Ok(42)Implementation of
mapOr()
mapOr<
U>(mapper,_defaultValue):U
Defined in: src/ok.ts:70
Maps the success value or returns the provided fallback when this result is Err.
Type Parameters
| Type Parameter | Description |
|---|---|
U | Return type. |
Parameters
| Parameter | Type | Description |
|---|---|---|
mapper | (value) => U | Function applied to the success value. |
_defaultValue | U | - |
Returns
U
See
- mapOrAsync - Async version.
- mapOrElse - Compute the fallback lazily.
Example
Result.ok(42).mapOr((x) => x * 2, 0) // 84
Result.err('fail').mapOr((x) => x * 2, 0) // 0Implementation of
mapOrElse()
mapOrElse<
U>(okMapper,_errMapper):U
Defined in: src/ok.ts:74
Maps either branch of the result into a shared output type.
Uses okMapper for Ok and errMapper for Err.
Type Parameters
| Type Parameter | Description |
|---|---|
U | Result type. |
Parameters
| Parameter | Type | Description |
|---|---|---|
okMapper | (value) => U | Function applied to the success value. |
_errMapper | (error) => U | - |
Returns
U
See
mapOrElseAsync - Async version.
Example
Result.ok(42).mapOrElse((x) => x * 2, () => -1)
// => 84
Result.err('fail').mapOrElse((x) => x * 2,() => -1)
// => -1