Skip to content

result

Minified5.00 KBMinzipped1.00 KB

Functional utilities for success | error types.

Overview

The types Ok<T> and Err<T> are expressed as plain objects, no wrapper classes are involved - you can act upon the raw objects however you wish and build your own functions around them:

ts
import type { Result, Ok, Err } from "@monstermann/result";
import { ok, err } from "@monstermann/result";

const a = ok(true);
const b: Ok<boolean> = { ok: true, value: true };

const c = err(false);
const d: Err<boolean> = { ok: false, error: false };

const e: Result<boolean, string> = { ok: true, value: true };
// Narrowed to Ok<boolean>
if (e.ok) console.log(e.value);
// Narrowed to Err<string>
if (!e.ok) console.log(e.error);

Async

Asynchronous results are simply expressed as Promise<Ok<T>> and Promise<Err<T>> and typically require no special constructors (eg. async (v) => ok(v) is enough).

ts
import { ResultAsync, ok } from "@monstermann/result";

const a = ok(5); // Ok<number>(5)
const b = ResultAsync.map(a, (x) => x * 2); // OkAsync<number>(10)
const c = ResultAsync.map(b, (x) => x * 2); // OkAsync<number>(20)

Pipe

Most functions come with "data-first" and "data-last" signatures, meaning they are pipe friendly:

ts
import { Result, ok } from "@monstermann/result"

Result.map(
    ok(5),
    (x) => x * 2
);
// Ok<number>

Result.map(
    err("fail"),
    (x) => x * 2
);
// Err<string>
ts
import { Result, ok } from "@monstermann/result"

pipe(
    ok(5),
    Result.map((x) => x * 2),
);
// Ok<number>

pipe(
    err("fail"),
    Result.map((x) => x * 2),
);
// Err<string>

Installation

sh
npm install @monstermann/result
sh
pnpm add @monstermann/result
sh
yarn add @monstermann/result
sh
bun add @monstermann/result

Tree-shaking

Installation

sh
npm install -D @monstermann/unplugin-result
sh
pnpm -D add @monstermann/unplugin-result
sh
yarn -D add @monstermann/unplugin-result
sh
bun -D add @monstermann/unplugin-result

Usage

ts
// vite.config.ts
import result from "@monstermann/unplugin-result/vite";

export default defineConfig({
    plugins: [result()],
});
ts
// rollup.config.js
import result from "@monstermann/unplugin-result/rollup";

export default {
    plugins: [result()],
};
ts
// rolldown.config.js
import result from "@monstermann/unplugin-result/rolldown";

export default {
    plugins: [result()],
};
ts
// webpack.config.js
const result = require("@monstermann/unplugin-result/webpack");

module.exports = {
    plugins: [result()],
};
ts
// rspack.config.js
const result = require("@monstermann/unplugin-result/rspack");

module.exports = {
    plugins: [result()],
};
ts
// esbuild.config.js
import { build } from "esbuild";
import result from "@monstermann/unplugin-result/esbuild";

build({
    plugins: [result()],
});

Alternatives