@pband/result (1.0.1-rc.3)
Installation
@pband:registry=https://git.pband.ch/api/packages/typescript/npm/npm install @pband/result@1.0.1-rc.3"@pband/result": "1.0.1-rc.3"About this package
result
Errors as values, as in Rust: a function that can fail returns a Result instead of
throwing, and the caller checks ok before it reaches the data. The methods are Rust's
Result API in camelCase.
import {err, ok, type Result} from '@pband/result'
function parse(input: string): Result<number, 'not a number'> {
const n = Number(input)
return Number.isNaN(n) ? err('not a number') : ok(n)
}
const r = parse('42')
if (r.ok)
r.data // 42, a number
else r.error // 'not a number'
parse('x').unwrapOr(0) // 0
Install
Published as @pband/result on a Gitea npm registry; no account or token is needed.
Map the scope in your app's .npmrc, then install it:
@pband:registry=https://git.pband.ch/api/packages/typescript/npm/
bun add @pband/result
Release candidates are published under the rc tag: bun add @pband/result@rc.
ESM only, with type declarations; runs on Node and Bun.
The type
Result<T, E = undefined> is either an Ok, with ok: true and its data: T, or an
Err, with ok: false and its error: E. Narrow on ok; instanceof is not part of
the API.
ok(data)builds an Ok.err(error)builds an Err.err()carries nothing, for aResult<T>whose failure needs no explanation.
E can be anything: a string, a string union, an object, an array.
Methods
They follow Rust's Result, in
camelCase. None is async: await first, then chain.
Inspect
isOkAnd(f),isErrAnd(f): whether it is an Ok (an Err) andfholds for its data (error).inspect(f),inspectErr(f): callfwith the data (error), if there is one, and return the same result.
Transform
map(f): an Ok off(data), or the same Err.mapErr(f): an Err off(error), or the same Ok.mapOr(fallback, f):f(data), orfallback.mapOrElse(fallbackFn, f):f(data), orfallbackFn(error).flatten(): on aResultof aResult, the inner one.
Combine
and(other):otherif this is an Ok, else this Err.andThen(f):f(data)if this is an Ok, else this Err.or(other): this Ok, orother.orElse(f): this Ok, orf(error).
Extract
unwrapOr(fallback),unwrapOrElse(f): the data, orfallback(f(error)).r.unwrapOr(null)givesT | null.expect(message),unwrap(): the data, or throw aPanic.expectErr(message),unwrapErr(): the error, or throw aPanic.
Where Rust would infer the other side of a result, the types take the union instead, so
ok(1).andThen(() => err('no')) is a Result<never, string> with no annotation.
Panic
Panic is the Error the unwrapping methods throw: a broken invariant, a state that
should be impossible. Its cause is the error (or, from expectErr and unwrapErr, the
data); err() has nothing to carry, so its Panic has no cause. unwrap uses Rust's message, called `Result::unwrap()` on an `Err` value; prefer
expect and say what was expected.
In SvelteKit, use expect in load, where handleError turns a throw into the error
page (error instanceof Panic tells it from other errors). Expected absence is not a
panic: a missing row is error(404, ...). Never use it in a form action or an event
handler: in an action it replaces the page and drops the user's input (return fail()
there); in a handler it reaches no error page at all.
combineAll
const r = await combineAll([getUser(id), getOrders(id)])
// Result<[User, Order[]], UserError | OrderError>
Waits for every promise, and returns an Ok of every data in order, or the first error in the order given (not the first to arrive).
Across a boundary
A Result is a class instance: sent as JSON (json(), socket.io, postMessage), it
arrives as a plain object without its methods. Unwrap at the edge: expect or
unwrapOr in load, fail() in an action, json(r.data) in an endpoint.
To return a Result from a SvelteKit load or action anyway, add the transporter to
src/hooks.ts:
import {transporter} from '@pband/result'
export const transport = {Result: transporter}
The transporter recognises its own classes: if an app ends up with two copies of
@pband/result, a Result from the other copy travels as a plain object.
Dependencies
Development Dependencies
| ID | Version |
|---|---|
| @eslint/js | ^10.0.1 |
| @types/bun | ^1.4.3 |
| devalue | ^6.0.3 |
| eslint | ^10.13.0 |
| jiti | ^2.7.0 |
| prettier | ^3.9.10 |
| typescript | ^6.0.3 |
| typescript-eslint | ^8.71.2 |