Rust-style Result<T, E> for TypeScript — type-safe error handling where errors become part of the return type, not invisible exceptions. ~900 bytes, zero dependencies.
function divide(a: number, b: number): Result<number, string> {
if (b === 0) return Err("division by zero");
return Ok(a / b);
}
const result = divide(10, 0);
if (result.ok)
console.log(result.value); // typed as number
else console.log(result.error); // typed as stringnpm install ts-result-typeimport { Ok, Err, Result } from "ts-result-type";
function divide(a: number, b: number): Result<number, string> {
if (b === 0) return Err("division by zero");
return Ok(a / b);
}
const result = divide(10, 2);
if (result.ok) {
console.log(result.value); // 5 — fully typed as number
} else {
console.log(result.error); // fully typed as string
}const message = Result.match(divide(10, 0), {
ok: (value) => `Result: ${value}`,
err: (error) => `Failed: ${error}`,
});
// "Failed: division by zero"const result = Result.flatMap(Ok("42"), (s) => {
const n = parseInt(s, 10);
return isNaN(n) ? Err("not a number") : Ok(n);
});
// Ok(42)import { fromThrowable, fromPromise } from "ts-result-type";
const parsed = fromThrowable(() => JSON.parse(input));
const data = await fromPromise(
fetch("/api/data").then((r) => r.json()),
(e) => `Fetch failed: ${(e as Error).message}`,
);| Function | Description |
|---|---|
Ok(value) |
Create a success result |
Err(error) |
Create an error result |
fromThrowable(fn, mapErr?) |
Wrap a function that might throw |
fromPromise(promise, mapErr?) |
Wrap a promise that might reject |
| Method | Description |
|---|---|
Result.map(result, fn) |
Transform the Ok value |
Result.mapErr(result, fn) |
Transform the Err value |
Result.flatMap(result, fn) |
Chain Result-returning functions |
Result.unwrap(result) |
Extract value or throw |
Result.unwrapOr(result, default) |
Extract value or use default |
Result.unwrapErr(result) |
Extract error or throw |
Result.match(result, { ok, err }) |
Pattern match on result |
Result.isOk(result) |
Type guard for Ok (narrows type) |
Result.isErr(result) |
Type guard for Err (narrows type) |
- Type safety — errors are part of the return type, not invisible
- Exhaustive handling — TypeScript ensures you handle both cases
- Composable — chain operations with
map,flatMap,match - Explicit — no hidden control flow, no forgotten catch blocks
README built with README Builder
MIT
