Skip to content

Class: Ok<T, E>

Defined in: src/ok.ts:8

Successful variant of Result.

See

Err - for the error variant

Example

ts
const result = Result.ok(42)

result.isOk()   // => true
result.unwrap() // => Ok(42)

Type Parameters

Type ParameterDefault typeDescription
T-Type of the success value
EneverError type carried by Result. Present only for union compatibility

Implements

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

ts
Result.err('failed').isErr() // => true
Result.ok(42).isErr()        // => false

Implementation of

Ok.isErr


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

ParameterType
_condition(error) => boolean

Returns

this is Err<T, E>

See

isOkAnd - Opposite check for success values.

Example

ts
Result.err('timeout').isErrAnd((e) => e === 'timeout') // => true
Result.ok(42).isErrAnd(() => true)                     // => false

Implementation of

Ok.isErrAnd


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

ts
Result.ok(42).isOk()        // => true
Result.err('failed').isOk() // => false

Implementation of

Ok.isOk


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

ParameterTypeDescription
condition(value) => booleanPredicate used to validate the success value.

Returns

this is Ok<T, E>

See

isErrAnd - Opposite check for errors.

Example

ts
Result.ok(42).isOkAnd((x) => x > 40)   // => true
Result.ok(10).isOkAnd((x) => x > 40)   // => false
Result.err('fail').isOkAnd(() => true) // => false

Implementation of

Ok.isOkAnd

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 ParameterDefault typeDescription
U-Next success value type.
E2neverNext error type.

Parameters

ParameterTypeDescription
otherResult<U, E2>Result returned when this result is Ok.

Returns

Result<U, E | E2>

See

Example

ts
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

Ok.and


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 ParameterDefault typeDescription
U-Next success value type.
E2neverNext error type.

Parameters

ParameterTypeDescription
next(value) => Result<U, E2>Function that returns the next result.

Returns

Result<U, E | E2>

See

Example

ts
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

Ok.andThen


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 ParameterDefault typeDescription
UTAlternative success type
E2neverAlternative error type

Parameters

ParameterType
_otherResult<U, E2>

Returns

Result<T | U, E2>

See

Example

ts
Result.ok(1).or(Result.ok(2))        // => Ok(1)
Result.err('fail').or(Result.ok(42)) // => Ok(42)

Implementation of

Ok.or


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 ParameterDefault typeDescription
UTRecovery success type
E2neverRecovery error type

Parameters

ParameterType
_fallback(error) => Result<U, E2>

Returns

Result<T | U, E2>

See

Example

ts
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

Ok.orElse

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 ParameterDefault typeDescription
U-Next success value type.
E2neverNext error type.

Parameters

ParameterTypeDescription
otherAsyncResult<U, E2>Async result returned when this result is Ok.

Returns

AsyncResult<U, E | E2>

See

and - Sync version

Example

ts
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

Ok.andAsync


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 ParameterDefault typeDescription
U-Next success value type.
E2neverNext error type.

Parameters

ParameterTypeDescription
next(value) => AsyncResult<U, E2>Async function that returns the next result.

Returns

AsyncResult<U, E | E2>

See

andThen - Sync version

Example

ts
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

Ok.andThenAsync


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 ParameterDefault typeDescription
UTAlternative success value type.
E2neverAlternative error type.

Parameters

ParameterType
_otherAsyncResult<U, E2>

Returns

AsyncResult<T | U, E2>

See

or - Sync version

Example

ts
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

Ok.orAsync


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 ParameterDefault typeDescription
UTRecovery success value type.
E2neverRecovery error type.

Parameters

ParameterType
_fallback(error) => AsyncResult<U, E2>

Returns

AsyncResult<T | U, E2>

See

orElse - sync version

Example

ts
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

Ok.orElseAsync

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 ParameterDescription
UMapped success value type.

Parameters

ParameterTypeDescription
mapper(value) => Promise<U>Async function applied to the success value.

Returns

AsyncResult<U, E>

See

map - sync version

Example

ts
await Result.ok(1).mapAsync(async (x) => x + 1)
// => Ok(2)

await Result.err('fail').mapAsync(async (x) => x + 1)
// => Err('fail')

Implementation of

Ok.mapAsync


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 ParameterDescription
E2Mapped error type.

Parameters

ParameterType
_mapper(error) => Promise<E2>

Returns

AsyncResult<T, E2>

See

mapErr - Sync version

Example

ts
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

Ok.mapErrAsync


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 ParameterDescription
UReturn type.

Parameters

ParameterTypeDescription
mapper(value) => Promise<U>Async function applied to the success value.
_defaultValueU-

Returns

Promise<U>

See

mapOr - Sync version

Example

ts
await Result.ok(5).mapOrAsync(async (x) => x * 2, 0)
// => 10

await Result.err('fail').mapOrAsync(async (x) => x * 2, 0)
// => 0

Implementation of

Ok.mapOrAsync


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 ParameterDescription
UResult type

Parameters

ParameterTypeDescription
okMapper(value) => Promise<U>Async function applied to the success value.
_errMapper(error) => Promise<U>-

Returns

Promise<U>

See

mapOrElse - Sync version

Example

ts
await Result.ok(5).mapOrElseAsync(
  async (x) => x * 2,
  async () => -1
)
// => 10

await Result.err('fail').mapOrElseAsync(
  async (x) => x * 2,
  async () => -1
)
// => -1

Implementation of

Ok.mapOrElseAsync

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 ParameterDescription
USecond success type
E2Second error type

Parameters

ParameterTypeDescription
otherResult<U, E2>Result to combine with this one.

Returns

Result<[T, U], E | E2>

See

zipWith - Combine and map in one step.

Example

ts
Result.ok(1).zip(Result.ok('a'))  // => Ok([1, 'a'])
Result.ok(1).zip(Result.err('b')) // => Err('b')

Implementation of

Ok.zip


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 ParameterDescription
USecond success value type.
RCombined return type.
E2Second error type.

Parameters

ParameterTypeDescription
otherResult<U, E2>Second result.
combine(value, otherValue) => RFunction applied to both success values.

Returns

Result<R, E | E2>

See

zip - Return a tuple instead of mapping.

Example

ts
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

Ok.zipWith

Constructors

Constructor

new Ok<T, E>(value): Ok<T, E>

Defined in: src/ok.ts:12

Parameters

ParameterType
valueT

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

NameTypeDefined in
type"ok"src/ok.ts:235
valueTsrc/ok.ts:235

Example

ts
Result.ok(42).toJSON()
// { type: 'ok', value: 42 }

Result.err('fail').toJSON()
// { type: 'err', error: 'fail' }

Implementation of

Ok.toJSON


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

ts
Result.ok(42).toNullable()        // => 42
Result.err('failed').toNullable() // => null

Implementation of

Ok.toNullable


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

ts
Result.ok(42).toString()      // => "Ok(42)"
Result.err('fail').toString() // => "Err("fail")"

Implementation of

Ok.toString


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

ts
Result.ok(42).toValue()        // => 42
Result.err('failed').toValue() // => undefined

Implementation of

Ok.toValue

Extraction

expect()

expect(_reason): T

Defined in: src/ok.ts:54

Returns the success value.

Parameters

ParameterType
_reasonstring

Returns

T

See

Throws

  • With reason and the original error as cause.

Examples

ts
Result.ok(42).expect('should exist')
// => 42
ts
Result.err('failed').expect('should exist')
// => throws Error("should exist", { cause: "failed" })

Implementation of

Ok.expect


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

ParameterTypeDescription
reasonstringCustom error message.

Returns

never

See

Throws

  • With reason and the original value as cause.

Examples

ts
Result.err('fail').expectErr('should be error')
// => 'fail'
ts
Result.ok(42).expectErr('should be error')
// => throws Error("should be error", { cause: 42 })

Implementation of

Ok.expectErr


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

ts
Result.ok(42).unwrap() // => 42
ts
Result.err('fail').unwrap()
// => throws Error("Called unwrap on an Err value", { cause: "fail" })
ts
if (result.isOk()) {
  result.unwrap() // safe
}

Implementation of

Ok.unwrap


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

ts
Result.err('failed').unwrapErr()
// => "failed"
ts
Result.ok(42).unwrapErr()
// => throws Error("Called unwrapErr on an Ok value", { cause: 42 })
ts
if (result.isErr()) {
  result.unwrapErr() // safe
}

Implementation of

Ok.unwrapErr


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 ParameterDefault type
UT

Parameters

ParameterType
_defaultValueU

Returns

T | U

See

Example

ts
Result.ok(42).unwrapOr(0)        // => 42
Result.err('failed').unwrapOr(0) // => 0

Implementation of

Ok.unwrapOr


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 ParameterDefault type
UT

Parameters

ParameterType
_fallback(error) => U

Returns

T | U

See

unwrapOr - Use a static fallback value.

Example

ts
Result.ok(42).unwrapOrElse((e) => e.length)        // => 42
Result.err('failed').unwrapOrElse((e) => e.length) // => 6

Implementation of

Ok.unwrapOrElse

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 ParameterDescription
UComparable value type.

Parameters

ParameterTypeDescription
valueUExpected value.
comparator?(actual, expected) => boolean-

Returns

boolean

Example

ts
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)            // => false

Implementation of

Ok.contains


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

ParameterTypeDescription
action(value) => voidCallback invoked with the success value.

Returns

this

See

Example

ts
Result.ok(42).inspect((value) => console.log(value))
// => logs 42, returns Ok(42)

Implementation of

Ok.inspect


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

ParameterType
_action(error) => void

Returns

this

See

inspect - Side effects for success values.

Example

ts
Result.err('fail').inspectErr(e => console.log(e))
// => logs "fail", returns Err("fail")

Implementation of

Ok.inspectErr


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 ParameterDescription
LReturn type for the success branch.
RReturn type for the error branch.

Parameters

ParameterTypeDescription
casesMatchCases<T, E, L, R>Branch handlers.

Returns

L | R

See

  • inspect - Run side effects for success values.
  • inspectErr - Run side effects for errors.

Examples

ts
Result.ok(5).match({
  ok: (x) => `Success: ${x * 2}`,
  err: (e) => `Error: ${e}`
})
// => "Success: 10"
ts
Result.err('not found').match({
  ok: (x) => `Value: ${x}`,
  err: (e) => `Error: ${e}`
})
// => "Error: not found"

Implementation of

Ok.match

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

ParameterTypeDescription
condition(value) => booleanPredicate used to validate the success value.
reason?stringOptional custom error message.

Returns

Result<T, Error>

See

Example

ts
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

Ok.filter


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 ParameterDescription
E2Additional error type.

Parameters

ParameterTypeDescription
condition(value) => booleanPredicate used to validate the success value.
onFailure(value) => E2Function used to create the failure value.

Returns

Result<T, E | E2>

See

filter - Use a default error message.

Example

ts
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

Ok.filterOrElse


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 ParameterDescription
UInner success value type.
E2Inner error type.

Parameters

ParameterType
thisOk<Result<U, E2>, E>

Returns

Result<U, E | E2>

Example

ts
Result.ok(Result.ok(42)).flatten()      // => Ok(42)
Result.ok(Result.err('fail')).flatten() // => Err("fail")
Result.err('outer').flatten()           // Err("outer")

Implementation of

Ok.flatten


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 ParameterDescription
UMapped success value type.

Parameters

ParameterTypeDescription
mapper(value) => UFunction 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

ts
Result.ok(42).map((x) => x * 2)      // => Ok(84)
Result.err('fail').map((x) => x * 2) // => Err("fail")

Implementation of

Ok.map


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 ParameterDescription
E2Mapped error type.

Parameters

ParameterType
_mapper(error) => E2

Returns

Result<T, E2>

See

mapErrAsync - Async version.

Example

ts
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

Ok.mapErr


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 ParameterDescription
UReturn type.

Parameters

ParameterTypeDescription
mapper(value) => UFunction applied to the success value.
_defaultValueU-

Returns

U

See

Example

ts
Result.ok(42).mapOr((x) => x * 2, 0)      // 84
Result.err('fail').mapOr((x) => x * 2, 0) // 0

Implementation of

Ok.mapOr


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 ParameterDescription
UResult type.

Parameters

ParameterTypeDescription
okMapper(value) => UFunction applied to the success value.
_errMapper(error) => U-

Returns

U

See

mapOrElseAsync - Async version.

Example

ts
Result.ok(42).mapOrElse((x) => x * 2, () => -1)
// => 84

Result.err('fail').mapOrElse((x) => x * 2,() => -1)
// => -1

Implementation of

Ok.mapOrElse