@ts-rust/std - v0.0.5
    Preparing search index...

    Interface Resultant<T, E>

    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.

    interface Resultant<T, E> {
        and<U>(x: Result<U, E>): Result<U, E>;
        andThen<U>(f: (x: T) => Result<U, E>): Result<U, E>;
        check(this: SettledResult<T, E>): readonly [false, CheckedError<E>];
        clone<U, F>(this: Result<Cloneable<U>, Cloneable<F>>): Result<U, F>;
        copy(): Result<T, E>;
        err(this: SettledResult<T, E>): Option<E>;
        expect(this: SettledResult<T, E>, msg?: string): T;
        expectErr(this: SettledResult<T, E>, msg?: string): CheckedError<E>;
        flatten<U, F>(this: Result<Result<U, F>, F>): Result<U, F>;
        inspect(f: (x: T) => unknown): Result<T, E>;
        inspectErr(f: (x: CheckedError<E>) => unknown): Result<T, E>;
        isErr(): this is Err<T, E>;
        isErrAnd(
            f: (x: CheckedError<E>) => boolean,
        ): this is Resultant<T, E> & { error: CheckedError<E> } & boolean;
        isOk(): this is Ok<T, E>;
        isOkAnd(
            f: (x: T) => boolean,
        ): this is Resultant<T, E> & { value: T } & boolean;
        iter(): IterableIterator<T, T, void>;
        map<U>(f: (x: T) => Awaited<U>): Result<U, E>;
        mapAll<U, F>(f: (x: Result<T, E>) => Result<U, F>): Result<U, F>;
        mapAll<U, F>(
            f: (x: Result<T, E>) => Promise<Result<U, F>>,
        ): PendingResult<Awaited<U>, Awaited<F>>;
        mapErr<F>(f: (e: E) => Awaited<F>): Result<T, F>;
        mapOr<U>(
            this: SettledResult<T, E>,
            def: Awaited<U>,
            f: (x: T) => Awaited<U>,
        ): U;
        mapOrElse<U>(
            this: SettledResult<T, E>,
            mkDef: () => Awaited<U>,
            f: (x: T) => Awaited<U>,
        ): U;
        match<U, F = U>(
            this: SettledResult<T, E>,
            f: (x: T) => Awaited<U>,
            g: (e: CheckedError<E>) => Awaited<F>,
        ): U | F;
        ok(): Option<T>;
        or<F>(x: Result<T, F>): Result<T, F>;
        orElse<F>(f: () => Result<T, F>): Result<T, F>;
        tap(f: (x: Result<T, E>) => unknown): Result<T, E>;
        toPending(): PendingResult<Awaited<T>, Awaited<E>>;
        toPendingCloned(
            this: Result<Cloneable<T>, Cloneable<E>>,
        ): PendingResult<Awaited<T>, Awaited<E>>;
        toString(): string;
        transpose<U, F>(this: Result<Option<U>, F>): Option<Result<U, F>>;
        try(
            this: SettledResult<T, E>,
        ): readonly [false, CheckedError<E>, undefined];
        unwrap(this: SettledResult<T, E>): T;
        unwrapErr(this: SettledResult<T, E>): CheckedError<E>;
        unwrapOr(this: SettledResult<T, E>, def: Awaited<T>): T;
        unwrapOrElse(this: SettledResult<T, E>, mkDef: () => Awaited<T>): T;
    }

    Type Parameters

    • T
    • E
    Index

    Methods

    • 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"));

      Type Parameters

      • U

      Parameters

      Returns Result<U, E>

    • 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"));

      Type Parameters

      • U

      Parameters

      Returns Result<U, E>

    • Inspects this result’s state, returning a tuple indicating success and either the value or error.

      • Returns [true, T] if this is an Ok, or [false, CheckedError<E>] if this is an Err.
      • Never throws, providing a safe way to access the result’s state without unwrapping.
      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" })]);

      Parameters

      Returns readonly [false, CheckedError<E>]

    • Returns a shallow copy of the Result.

      const value = { a: 1 };
      const x = ok<{ a: number }, string>(value);

      expect(x.copy()).toStrictEqual(ok({ a: 1 }));
      expect(x.copy()).not.toBe(x); // Different result reference
      expect(x.copy().unwrap()).toBe(value); // Same value reference

      Returns Result<T, E>

    • Flattens 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");

      Type Parameters

      • U
      • F

      Parameters

      Returns Result<U, F>

    • Calls f with the value if this result is an Ok, then returns a copy of this result.

      • Returns a new Result instance, not the original reference.
      • If 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

      Parameters

      • f: (x: T) => unknown

      Returns Result<T, E>

    • Calls f with the value if this result is an Err, then returns a copy of this result.

      • Returns a new Result instance, not the original reference.
      • If 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);

      Parameters

      Returns Result<T, E>

    • Checks if this result is an Err, narrowing its type to Err if true.

      const x = ok<number, string>(2);
      const y = err<number, string>("failure");

      expect(x.isErr()).toBe(false);
      expect(y.isErr()).toBe(true);

      Returns this is Err<T, E>

    • Returns true if the result is Err and f returns true for the contained error.

      • Default: If 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);

      Parameters

      Returns this is Resultant<T, E> & { error: CheckedError<E> } & boolean

    • Checks if this result is an Ok, narrowing its type to Ok if true.

      const x = ok<number, string>(2);
      const y = err<number, string>("failure");

      expect(x.isOk()).toBe(true);
      expect(y.isOk()).toBe(false);

      Returns this is Ok<T, E>

    • Returns true if the result is Ok and f returns true for the contained value.

      • Default: If 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);

      Parameters

      • f: (x: T) => boolean

      Returns this is Resultant<T, E> & { value: T } & boolean

    • Returns an iterator over this result’s value, yielding it if Ok or nothing if Err.

      • Yields exactly one item for Ok, or zero items for Err.
      • Compatible with for...of loops and spread operators.
      • Ignores the error value in Err cases, focusing only on the success case.
      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([]);

      Returns IterableIterator<T, T, void>

    • Transforms this result by applying f to the value if it’s an Ok, or preserves the Err unchanged.

      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"));

      Type Parameters

      • U

      Parameters

      Returns Result<U, E>

    • 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.

      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();

      Type Parameters

      • U
      • F

      Parameters

      Returns Result<U, F>

    • 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.

      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();

      Type Parameters

      • U
      • F

      Parameters

      Returns PendingResult<Awaited<U>, Awaited<F>>

    • Transforms this result by applying f to the error if it’s an Err with an expected error, or preserves the Ok unchanged.

      • If f throws, returns an Err with an UnexpectedError containing the original error.
      • If this is an Err with an UnexpectedError, 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();

      Type Parameters

      • F

      Parameters

      Returns Result<T, F>

    • Returns f applied to the value if Ok, otherwise returns def.

      • Default: If 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);

      Type Parameters

      • U

      Parameters

      Returns U

    • Returns f applied to the contained value if Ok, otherwise returns the result of mkDef.

      • If 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);

      Type Parameters

      • U

      Parameters

      Returns U

    • Matches this result, returning f applied to the value if Ok, or g applied to the CheckedError if Err.

      • If 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);

      Type Parameters

      • U
      • F = U

      Parameters

      Returns U | F

    • 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"));

      Type Parameters

      • F

      Parameters

      Returns Result<T, F>

    • Returns the current result if Ok, otherwise returns the result of f.

      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"));

      Type Parameters

      • F

      Parameters

      Returns Result<T, F>

    • 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.

      • If f throws or rejects, the error is silently ignored.
      • If 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' }");

      Parameters

      Returns Result<T, E>

    • Generates a string representation of this result, reflecting its current state.

      const x = ok<number, string>(2);
      const y = err<number, string>("error");

      expect(x.toString()).toBe("Ok { 2 }");
      expect(y.toString()).toBe("Err { 'error' }");

      Returns string

    • 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")));

      Type Parameters

      • U
      • F

      Parameters

      Returns Option<Result<U, F>>

    • Extracts this result’s state, returning a tuple with a success flag, error, and value.

      Inspired by the Try Operator proposal.

      • Returns [true, undefined, T] if this is an Ok, or [false, CheckedError<E>, undefined] if this is an Err.
      • Never throws, offering a safe way to inspect the result’s state with explicit success indication.
      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]);

      Parameters

      Returns readonly [false, CheckedError<E>, undefined]