Thanks to visit codestin.com
Credit goes to github.com

Skip to content

lppedd/mini-result

Repository files navigation

mini-result

Minimal Result type for TypeScript

npm ecmascript status build coverage minified size license

Design considerations

mini-result is inspired by existing Result-type libraries such as:

However, unlike these libraries, mini-result intentionally focuses on minimalism. Rather than looking for features, tree-shakability or performance, it aims to provide a tiny and easy-to-understand Result type with just the essentials needed for practical error handling, which also includes async support.

The minified package currently sits at around 0.5 kB, and no further API additions are planned.

Installation

npm i @lppedd/mini-result
pnpm add @lppedd/mini-result
yarn add @lppedd/mini-result

Operations

Fundamentally, Result offers only 5 operations: map, tap, catch, unwrap and unwrapOr.
Those operations are also split into synchronous and asynchronous (suffixed with *Async) variants.

But let's start with creating an Ok or Err result.

Result factory

import { Res } from "@lppedd/mini-result";

const ok = Res.ok(1);        // Ok<number, never>
const er = Res.err("error"); // Err<never, string>

Result.map

Transforms the result's success value. No-op if the result represents an error state.

// result: Result<number, Error>
const r = result.map((n) => n + 1);
const r = result.map((n) => compute(n)); // () => Result<number, Error>

Result.tap

Invokes a function with the result's success value if the result represents a success state, or with the error value if it represents an error state.

// result: Result<number, Error>
const r = result.tap((n) => console.log(n), (e) => console.error(e));

Result.catch

Catches and transforms the result's error value. No-op if the result represents a success state.

// result: Result<number, Error>
// Transform the error value from Error to string
const r = result.catch((e) => Res.err(e.message));

// Replace the error value with a success value
const r = result.catch((e) => defaultValue);
// Or
const r = result.catch((e) => Res.ok(defaultValue));

// Replace the error value with a new result (which might be a success or error itself)
const r = result.catch((e) => computeDefault()); // (e) => Result<number, Error>

Result.unwrap

Unwraps the result's success value.

// result: Result<number, Error>
// n: number
const n = result.unwrap();

Or throws an Error if the result represents an error state.

[mini-result] cannot unwrap an Err result
  [value] Error: invalid number

Result.unwrapOr

Unwraps the result's success value, or falls back to the value returned by the given function if the result represents an error state.

// result: Result<number, Error>
// n: number
const n = result.unwrapOr((e) => defaultValue);

License

MIT 2025-present Edoardo Luppi