Skip to content

Class: Err<T, E>

Defined in: src/err.ts:7

Failure variant of Result.

See

Ok - for the success variant

Example

ts
const result = Result.err('failed')

result.isErr()     // => true
result.unwrapErr() // => Err("failed")

Type Parameters

Type ParameterDefault typeDescription
TneverSuccess type carried by Result. Present only for union compatibility.
EErrorType of the stored error.

Implements

Type Guards

isErr()

isErr(): this is Err<T, E>

Defined in: src/err.ts:21

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

Err.isErr


isErrAnd()

isErrAnd(condition): this is Err<T, E>

Defined in: src/err.ts:29

Returns true when this result is Err and its error satisfies the provided predicate.

Parameters

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

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

Err.isErrAnd


isOk()

isOk(): this is Ok<T, E>

Defined in: src/err.ts:17

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

Err.isOk


isOkAnd()

isOkAnd(_condition): this is Ok<T, E>

Defined in: src/err.ts:25

Returns true when this result is Ok and its value satisfies the provided predicate.

Parameters

ParameterType
_condition(value) => boolean

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

Err.isOkAnd

Alternation

and()

and<U, E2>(_other): Result<U, E | E2>

Defined in: src/err.ts:100

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

ParameterType
_otherResult<U, E2>

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

Err.and


andThen()

andThen<U, E2>(_next): Result<U, E | E2>

Defined in: src/err.ts:104

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

ParameterType
_next(value) => Result<U, E2>

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

Err.andThen


or()

or<U, E2>(other): Result<T | U, E2>

Defined in: src/err.ts:108

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

ParameterTypeDescription
otherResult<U, E2>Result used when this result is Err.

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

Err.or


orElse()

orElse<U, E2>(fallback): Result<T | U, E2>

Defined in: src/err.ts:112

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

ParameterTypeDescription
fallback(error) => Result<U, E2>Function used to recover from an error.

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

Err.orElse

Async Alternation

andAsync()

andAsync<U, E2>(_other): AsyncResult<U, E | E2>

Defined in: src/err.ts:179

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

ParameterType
_otherAsyncResult<U, E2>

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

Err.andAsync


andThenAsync()

andThenAsync<U, E2>(_next): AsyncResult<U, E | E2>

Defined in: src/err.ts:183

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

ParameterType
_next(value) => AsyncResult<U, E2>

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

Err.andThenAsync


orAsync()

orAsync<U, E2>(other): AsyncResult<T | U, E2>

Defined in: src/err.ts:187

Returns this result when it is Ok, otherwise returns other.

Type Parameters

Type ParameterDefault typeDescription
UTAlternative success value type.
E2neverAlternative error type.

Parameters

ParameterTypeDescription
otherAsyncResult<U, E2>Async fallback result.

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

Err.orAsync


orElseAsync()

orElseAsync<U, E2>(fallback): AsyncResult<T | U, E2>

Defined in: src/err.ts:191

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

ParameterTypeDescription
fallback(error) => AsyncResult<U, E2>Async function used to recover from an error.

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

Err.orElseAsync

Async Transformation

mapAsync()

mapAsync<U>(_mapper): AsyncResult<U, E>

Defined in: src/err.ts:156

Asynchronously transforms the success value.

If this result is Err, the original error is preserved.

Type Parameters

Type ParameterDescription
UMapped success value type.

Parameters

ParameterType
_mapper(value) => Promise<U>

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

Err.mapAsync


mapErrAsync()

mapErrAsync<E2>(mapper): AsyncResult<T, E2>

Defined in: src/err.ts:160

Asynchronously transforms the error value.

If this result is Ok, the original success value is preserved.

Type Parameters

Type ParameterDescription
E2Mapped error type.

Parameters

ParameterTypeDescription
mapper(error) => Promise<E2>Async function applied to the error value.

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

Err.mapErrAsync


mapOrAsync()

mapOrAsync<U>(_mapper, defaultValue): Promise<U>

Defined in: src/err.ts:164

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>-
defaultValueUValue returned when this result is Err.

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

Err.mapOrAsync


mapOrElseAsync()

mapOrElseAsync<U>(_okMapper, errMapper): Promise<U>

Defined in: src/err.ts:168

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>-
errMapper(error) => Promise<U>Async function applied to the error value.

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

Err.mapOrElseAsync

Combination

zip()

zip<U, E2>(_other): Result<[T, U], E | E2>

Defined in: src/err.ts:120

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

ParameterType
_otherResult<U, E2>

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

Err.zip


zipWith()

zipWith<U, R, E2>(_other, _combine): Result<R, E | E2>

Defined in: src/err.ts:124

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

ParameterType
_otherResult<U, E2>
_combine(value, otherValue) => R

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

Err.zipWith

Constructors

Constructor

new Err<T, E>(error): Err<T, E>

Defined in: src/err.ts:11

Parameters

ParameterType
errorE

Returns

Err<T, E>

Conversion

toJSON()

toJSON(): object

Defined in: src/err.ts:205

Converts this result into a plain JSON-serializable object.

Returns

object

NameTypeDefined in
errorEsrc/err.ts:205
type"err"src/err.ts:205

Example

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

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

Implementation of

Err.toJSON


toNullable()

toNullable(): null

Defined in: src/err.ts:209

Converts this result into a nullable value.

Returns the success value when this result is Ok, otherwise returns null.

Returns

null

See

toValue - Return undefined on error instead.

Example

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

Implementation of

Err.toNullable


toString()

toString(): string

Defined in: src/err.ts:201

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

Err.toString


toValue()

toValue(): T | undefined

Defined in: src/err.ts:213

Converts this result into an optional value.

Returns the success value when this result is Ok, otherwise returns undefined.

Returns

T | undefined

See

toNullable - Return null on error instead.

Example

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

Implementation of

Err.toValue

Extraction

expect()

expect(reason): never

Defined in: src/err.ts:53

Returns the success value.

Parameters

ParameterTypeDescription
reasonstringCustom error message.

Returns

never

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

Err.expect


expectErr()

expectErr(_reason): E

Defined in: src/err.ts:57

Returns the error value.

Throws with the provided message if this result is Ok.

Parameters

ParameterType
_reasonstring

Returns

E

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

Err.expectErr


unwrap()

unwrap(): never

Defined in: src/err.ts:37

Returns the contained success value.

Throws if this result is Err.

Returns

never

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

Err.unwrap


unwrapErr()

unwrapErr(): E

Defined in: src/err.ts:41

Returns the contained error value.

Throws if this result is Ok.

Returns

E

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

Err.unwrapErr


unwrapOr()

unwrapOr<U>(defaultValue): T | U

Defined in: src/err.ts:45

Returns the success value, or the provided fallback when this result is Err.

Type Parameters

Type ParameterDefault type
UT

Parameters

ParameterTypeDescription
defaultValueUValue returned when this result is Err.

Returns

T | U

See

Example

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

Implementation of

Err.unwrapOr


unwrapOrElse()

unwrapOrElse<U>(fallback): T | U

Defined in: src/err.ts:49

Returns the success value, or computes a fallback from the error when this result is Err.

Type Parameters

Type ParameterDefault type
UT

Parameters

ParameterTypeDescription
fallback(error) => UFunction used to derive a fallback from the error.

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

Err.unwrapOrElse

Inspection

contains()

contains<U>(_value, _comparator?): boolean

Defined in: src/err.ts:134

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

ParameterType
_valueU
_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

Err.contains


inspect()

inspect(_action): this

Defined in: src/err.ts:142

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

ParameterType
_action(value) => void

Returns

this

See

Example

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

Implementation of

Err.inspect


inspectErr()

inspectErr(action): this

Defined in: src/err.ts:146

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

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

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

Err.inspectErr


match()

match<L, R>(cases): L | R

Defined in: src/err.ts:138

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

Err.match

Transformation

filter()

filter(_condition, _reason?): Result<T, Error>

Defined in: src/err.ts:81

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

ParameterType
_condition(value) => boolean
_reason?string

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

Err.filter


filterOrElse()

filterOrElse<E2>(_condition, _onFailure): Result<T, E | E2>

Defined in: src/err.ts:85

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

ParameterType
_condition(value) => boolean
_onFailure(value) => E2

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

Err.filterOrElse


flatten()

flatten<U, E2>(this): Result<U, E | E2>

Defined in: src/err.ts:92

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
thisErr<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

Err.flatten


map()

map<U>(_mapper): Result<U, E>

Defined in: src/err.ts:65

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

ParameterType
_mapper(value) => U

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

Err.map


mapErr()

mapErr<E2>(mapper): Result<T, E2>

Defined in: src/err.ts:77

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

ParameterTypeDescription
mapper(error) => E2Function applied to the error value.

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

Err.mapErr


mapOr()

mapOr<U>(_mapper, defaultValue): U

Defined in: src/err.ts:69

Maps the success value or returns the provided fallback when this result is Err.

Type Parameters

Type ParameterDescription
UReturn type.

Parameters

ParameterTypeDescription
_mapper(value) => U-
defaultValueUValue returned when this result is Err.

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

Err.mapOr


mapOrElse()

mapOrElse<U>(_okMapper, errMapper): U

Defined in: src/err.ts:73

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) => U-
errMapper(error) => UFunction applied to the error value.

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

Err.mapOrElse