Returns x
if this result is Ok, otherwise returns the Err
value of self.
const x = ok<number, string>(1);
const y = ok<number, string>(2);
const z = err<number, string>("failure");
expect(x.and(y)).toStrictEqual(ok(2));
expect(x.and(z)).toStrictEqual(err("failure"));
expect(z.and(x)).toStrictEqual(err("failure"));
Applies f
to the value if this result is Ok and returns its result,
otherwise returns the Err value of self.
const x = ok<number, string>(2);
const y = err<number, string>("failure");
expect(x.andThen(n => ok(n * 2))).toStrictEqual(ok(4));
expect(y.andThen(n => ok(n * 2))).toStrictEqual(err("failure"));
Inspects this result’s state, returning a tuple indicating success and either the value or error.
[true, T]
if this is an Ok, or [false, CheckedError<E>]
if this is an Err.const x = ok<number, string>(42);
const y = err<number, string>("failure");
expect(x.check()).toEqual([true, 42]);
expect(y.check()).toEqual([false, expect.objectContaining({ expected: "failure" })]);
Returns a deep copy of the Result.
Only available on Results with Cloneable value and error.
const x = ok(1);
const y = ok({ a: 1, clone: () => ({ a: 0 }) });
expect(x.clone()).toStrictEqual(ok(1));
expect(x.clone()).not.toBe(x); // Different reference
expect(x.clone().unwrap()).toBe(1);
expect(y.clone()).toStrictEqual(ok({ a: 0 }));
Converts this Result to an Option<E> containing the error, if present.
Returns Some with the error value if this is an Err, or None if this is an Ok.
const x = ok<number, string>(1);
const y = err<number, string>("failure");
expect(x.err()).toStrictEqual(none());
expect(y.err()).toStrictEqual(some("failure"));
Retrieves the value if this result is an Ok, or throws a ResultError with an optional message if it’s an Err.
const x = ok<number, string>(42);
const y = err<number, string>("failure");
expect(x.expect("Failed!")).toBe(42);
expect(() => y.expect("Failed!")).toThrow(ResultError);
Optional
msg: stringRetrieves the error if this result is an Err, or throws a ResultError with an optional message if it’s an Ok.
const x = ok<number, string>(42);
const y = err<number, string>("failure");
expect(() => x.expectErr("Failed!")).toThrow(ResultError);
expect(isCheckedError(y.expectErr("Failed!"))).toBe(true);
expect(y.expectErr("Failed!").expected).toBe("failure");
Optional
msg: stringFlattens a nested result (Result<Result<T, E>, E>
) into a single result
(Result<T, E>
).
const x: Result<Result<Result<number, string>, string>, string> = ok(ok(ok(6)));
const y: Result<Result<number, string>, string> = x.flatten();
const z: Result<Result<number, string>, string> = err("oops");
expect(x.flatten()).toStrictEqual(ok(ok(6)));
expect(y.flatten()).toStrictEqual(ok(6));
expect(z.flatten().expected).toBe("oops");
Calls f
with the value if this result is an Ok, then returns
a copy of this result.
f
throws or returns a Promise
that rejects, the error is ignored.const x = ok<number, string>(2);
const y = err<number, string>("failure");
let sideEffect = 0;
expect(x.inspect(n => (sideEffect = n))).toStrictEqual(ok(2));
expect(x.inspect(_ => { throw new Error() })).toStrictEqual(ok(2));
expect(sideEffect).toBe(2);
expect(y.inspect(n => (sideEffect = n))).toStrictEqual(err("failure"));
expect(sideEffect).toBe(2); // Unchanged
Calls f
with the value if this result is an Err, then returns
a copy of this result.
f
throws or returns a Promise
that rejects, the error is ignored.const x = ok<number, string>(2);
const y = err<number, string>("failure");
let sideEffect = 0;
expect(x.inspect(n => (sideEffect = n))).toStrictEqual(ok(2));
expect(x.inspect(_ => { throw new Error() })).toStrictEqual(ok(2));
expect(sideEffect).toBe(0);
expect(y.inspect(n => (sideEffect = n))).toStrictEqual(err("failure"));
expect(y.inspect(_ => { throw new Error() })).toStrictEqual(err("failure"));
expect(sideEffect).toBe(2);
Returns true
if the result is Err and f
returns true
for the contained error.
f
throws, false
is returned.const x = ok<number, string>(2);
const y = err<number, string>("failure");
expect(x.isErrAnd(e => e.expected === "failure")).toBe(false);
expect(y.isErrAnd(e => e.expected === "failure")).toBe(true);
expect(y.isErrAnd(e => Boolean(e.unexpected))).toBe(false);
Returns true
if the result is Ok and f
returns true
for the contained value.
f
throws, false
is returned.const x = ok<number, string>(2);
const y = err<number, string>("failure");
expect(x.isOkAnd(n => n > 0)).toBe(true);
expect(x.isOkAnd(n => n < 0)).toBe(false);
expect(y.isOkAnd(n => true)).toBe(false);
Returns an iterator over this result’s value, yielding it if Ok or nothing if Err.
for...of
loops and spread operators.const x = ok<number, string>(42);
const y = err<number, string>("failure");
const iterX = x.iter();
expect(iterX.next()).toEqual({ value: 42, done: false });
expect(iterX.next()).toEqual({ done: true });
const iterY = y.iter();
expect(iterY.next()).toEqual({ done: true });
expect([...x.iter()]).toEqual([42]);
expect([...y.iter()]).toEqual([]);
Transforms this result by applying f
to the value if it’s an Ok,
or preserves the Err unchanged.
f
throws, returns an Err with an UnexpectedError
containing the original error.const x = ok<number, string>(2);
const y = err<number, string>("failure");
expect(x.map(n => n * 2)).toStrictEqual(ok(4));
expect(x.map(() => { throw new Error("boom") }).unwrapErr().unexpected).toBeDefined();
expect(y.map(n => n * 2)).toStrictEqual(err("failure"));
Maps this result by applying a callback to its full state, executing the callback for both Ok and Err, returning a new Result.
Unlike andThen, which only invokes the callback
for Ok, this method always calls f
, passing the entire Result
as its argument.
f
throws an Err with an UnexpectedError is returned.const okRes = ok<number, string>(42);
const errRes = err<number, string>("failure");
expect(okRes.mapAll(res => ok(res.unwrapOr(0) + 1))).toStrictEqual(ok(43));
expect(errRes.mapAll(res => ok(res.unwrapOr(0) + 1))).toStrictEqual(ok(1));
expect(okRes.mapAll(res => res.isOk() ? ok("success") : err("fail"))).toStrictEqual(ok("success"));
expect(errRes.mapAll(() => { throw new Error("boom") }).unwrapErr().unexpected).toBeDefined();
Maps this result by applying a callback to its full state, executing the callback for both Ok and Err, returning a new PendingResult.
Unlike andThen, which only invokes the callback
for Ok, this method always calls f
, passing the entire
Result as its argument.
f
returns a Promise
that rejects, the resulting PendingResult
resolves to an Err with an UnexpectedError.const okRes = ok<number, string>(42);
const errRes = err<number, string>("failure");
const mappedOk = okRes.mapAll(res => Promise.resolve(ok(res.unwrapOr(0) + 1)));
expect(await mappedOk).toStrictEqual(ok(43));
const mappedErr = errRes.mapAll(res => Promise.resolve(ok(res.unwrapOr(0) + 1)));
expect(await mappedErr).toStrictEqual(ok(1));
const mappedCheck = okRes.mapAll(res => Promise.resolve(res.isOk() ? ok("success") : err("fail")));
expect(await mappedCheck).toStrictEqual(ok("success"));
const mappedThrow = errRes.mapAll(() => Promise.reject(new Error("boom")));
expect((await mappedThrow).unwrapErr().unexpected).toBeDefined();
Transforms this result by applying f
to the error if it’s an Err
with an expected error, or preserves the Ok unchanged.
f
throws, returns an Err with an UnexpectedError
containing the original error.f
is not called,
and the original error is preserved.const x = ok<number, string>(2);
const y = err<number, string>("failure");
expect(x.mapErr(e => e.length)).toStrictEqual(ok(2));
expect(y.mapErr(e => e.length)).toStrictEqual(err(7));
expect(y.mapErr(() => { throw new Error("boom") }).unwrapErr().unexpected).toBeDefined();
Returns f
applied to the value if Ok, otherwise returns def
.
f
throws, returns def
.const x = ok<number, string>(2);
const y = err<number, string>("failure");
expect(x.mapOr(0, n => n * 2)).toBe(4);
expect(x.mapOr(0, () => { throw new Error("boom") }).unwrapErr().unexpected).toBeDefined();
expect(y.mapOr(0, n => n * 2)).toBe(0);
Returns f
applied to the contained value if Ok, otherwise
returns the result of mkDef
.
mkDef
is called and throws an exception, with
the original error set as ResultError.reason.f
throws, the error is silently ignored, and the result of mkDef
is returned.const x = ok<number, string>(2);
const y = err<number, string>("failure");
expect(x.mapOrElse(() => 0, n => n * 2)).toBe(4);
expect(x.mapOrElse(() => 1, () => { throw new Error("boom") })).toBe(1);
expect(() => y.mapOrElse(() => { throw new Error("boom") }, n => n * 2)).toThrow(ResultError);
expect(y.mapOrElse(() => 0, n => n * 2)).toBe(0);
Matches this result, returning f
applied to the value if Ok,
or g
applied to the CheckedError if Err.
f
or g
throws an exception, with the original
error set as ResultError.reason.f
or g
return a Promise
that rejects, the caller is responsible
for handling the rejection.const x = ok<number, string>(2);
const y = err<number, string>("failure");
expect(x.match(n => n * 2, () => 0)).toBe(4);
expect(() => x.match(_ => { throw new Error() }, () => 0)).toThrow(ResultError);
expect(y.match(n => n * 2, e => e.expected.length)).toBe(7);
expect(() => y.match(n => n * 2, () => { throw new Error() })).toThrow(ResultError);
Returns the current result if it is Ok, otherwise returns x
.
const x = ok<number, string>(2);
const y = err<number, string>("failure");
expect(x.or(ok(3))).toStrictEqual(ok(2));
expect(x.or(err("failure"))).toStrictEqual(ok(2));
expect(y.or(ok(3))).toStrictEqual(ok(3));
expect(y.or(err("another one"))).toStrictEqual(err("failure"));
Returns the current result if Ok, otherwise returns the result of f
.
f
throws, returns an Err with an UnexpectedError
containing the original error.const x = ok<number, string>(2);
const y = err<number, string>("failure");
expect(x.orElse(() => ok(3))).toStrictEqual(ok(2));
expect(y.orElse(() => ok(3))).toStrictEqual(ok(3));
expect(y.orElse(() => { throw new Error("boom") }).unwrapErr().unexpected).toBeDefined();
expect(y.orElse(() => err("another one"))).toStrictEqual(err("another one"));
Executes f
with a copy of this result, then returns a new copy unchanged.
Useful for side-effects like logging, works with both Ok and Err.
f
throws or rejects, the error is silently ignored.f
returns a promise, the promise is not awaited before returning.const x = ok<number, string>(42);
const y = err<number, string>("failure");
let log = "";
expect(x.tap(res => (log = res.toString()))).toStrictEqual(ok(42));
expect(log).toBe("Ok { 42 }");
expect(y.tap(res => (log = res.toString()))).toStrictEqual(err("failure"));
expect(log).toBe("Err { 'failure' }");
Converts this result to a PendingResult using a shallow copy of its current state.
PromiseLike
value to
a PendingResult with an Awaited
value.const value = { a: 1 };
const x = ok<{ a: number }, string>(value);
const pendingX = x.toPending();
expect(isPendingResult(pendingX)).toBe(true);
expect(await pendingX).toStrictEqual(ok({ a: 1 }));
value.a = 2;
expect(await pendingX).toStrictEqual(ok({ a: 2 }));
Converts this result to a PendingResult using a deep clone of its current state.
PromiseLike
value to
a PendingResult with an Awaited
value, preserving independence
from the original data.const value = { a: 1, clone: () => ({ a: 0 }) };
const x = ok(value);
const pendingX = x.toPendingCloned();
expect(isPendingResult(pendingX)).toBe(true);
expect((await pendingX).unwrap()).toStrictEqual({ a: 0 });
value.a = 42;
expect((await pendingX).unwrap()).toStrictEqual({ a: 0 });
Transposes a Result of an Option into an Option of a Result.
Maps Ok(None)
to None
, Ok(Some(_))
to Some(Ok(_))
and
Err(_)
to Some(Err(_))
.
const x = ok<Option<number>, string>(none());
const y = ok<Option<number>, string>(some(2));
const z = err<Option<number>, string>("error");
expect(x.transpose()).toStrictEqual(none());
expect(y.transpose()).toStrictEqual(some(ok(2)));
expect(z.transpose()).toStrictEqual(some(err("error")));
Extracts this result’s state, returning a tuple with a success flag, error, and value.
Inspired by the Try Operator proposal.
[true, undefined, T]
if this is an Ok, or
[false, CheckedError<E>, undefined]
if this is an Err.const x = ok<number, string>(42);
const y = err<number, string>("failure");
expect(x.try()).toEqual([true, undefined, 42]);
expect(y.try()).toEqual([false, expect.objectContaining({ expected: "failure" }), undefined]);
Retrieves the value if this result is an Ok, or throws a ResultError if it’s an Err.
const x = ok<number, string>(42);
const y = err<number, string>("failure");
expect(x.unwrap()).toBe(42);
expect(() => y.unwrap()).toThrow(ResultError);
Retrieves the CheckedError if this result is an Err, or throws a ResultError if it’s an Ok.
const x = ok<number, string>(42);
const y = err<number, string>("failure");
expect(() => x.unwrapErr()).toThrow(ResultError);
expect(y.unwrapErr().expected).toBe("failure");
Returns the contained value if Ok, or the result of mkDef
if Err.
mkDef
throws, with the original error set as
ResultError.reason.const x = ok<number, string>(2);
const y = err<number, string>("failure");
expect(x.unwrapOrElse(() => 0)).toBe(2);
expect(y.unwrapOrElse(() => 0)).toBe(0);
expect(() => y.unwrapOrElse(() => { throw new Error("boom") })).toThrow(ResultError);
Interface representing the resultant state of an operation, either a success (Ok<T>) or an error (Err<E>).
Inspired by Rust’s Result, it provides a type-safe alternative to exceptions for handling success or failure outcomes.