Rust style Result for TypeScript
npm install @bulatlib/resSmall, strict utilities for Rust‑style (Ok/Err) results. Provides safe constructors, execution wrappers, and transformation chains via pipe.
``bash`
npm i @bulatlib/resor
pnpm add @bulatlib/resor
bun add @bulatlib/res
- Core types
- Res: union { ok: T; err?: never } | { ok?: never; err: Error }.
- Constructors
- ok(value) — create a successful result.err(error)
- — create an error result.
- Safe execution
- wrap(fn) — run a sync function with try/catch and return Res.wrapAsync(fn)
- — run an async function with try/catch and return Promise.
- Pipe
- pipe.from(res) — wraps Res and returns Pipe with chainable methods.Pipe
- map(fn)
- — Ok(T) -> Ok(fn(T)), Err unchanged.mapErr(fn)
- — transform Error to Err(fn(err)).mapOr(default, fn)
- — on Ok return Ok(fn(T)), on Err return Ok(default).mapOrElse(defaultFn, fn)
- — on Ok return Ok(fn(T)), on Err return Ok(defaultFn(err)).and(res)
- — if Ok, return the second res, otherwise keep original Err.andThen(fn)
- — if Ok, evaluate fn(T): Res, otherwise Err.or(res)
- — if Ok, return it; otherwise return the second res.orElse(fn)
- — if Err, evaluate fn(err): Res; otherwise keep original Ok.unwrapOr(default)
- — return T or default.unwrapOrElse(fn)
- — return T or fn(err).match({ ok, err })
- — pattern match and return a value of one of callbacks.res()
- — return raw Res.
- Utilities
- combine(results) — fold Res into Res. Returns the first Err if any, otherwise Ok with collected values in order.
Examples will be added soon. Meanwhile, please check the test files in src (e.g., src/*.test.ts`) for usage examples.
MIT