Skip to content
better-result
Esc
navigateopen⌘Jpreview
On this page

A better Result type for TypeScript

Lightweight Result type for TypeScript with generator-based composition.

TypeScript-first zero runtime dependencies

better-result makes expected failure explicit without turning your application into nested conditionals. A value is either Ok<T> or Err<E>, and TypeScript carries both possibilities to the place where you decide what to do.

import { Result, TaggedError } from "better-result";

class InvalidPort extends TaggedError("InvalidPort")<{
  input: string;
  message: string;
}> {}

const parsePort = (input: string) => {
  const port = Number(input);
  return Number.isInteger(port) && port > 0
    ? Result.ok(port)
    : Result.err(new InvalidPort({ input, message: "Port must be a positive integer" }));
};

const address = parsePort("3000").map((port) => `http://localhost:${port}`);
// Result<string, InvalidPort>

Start in sixty seconds

Install

npm install better-result

Create a Result

const parsed = Result.try(() => JSON.parse(input));
// Result<unknown, UnhandledException>

Handle both branches

const message = parsed.match({
  ok: (value) => `Parsed ${JSON.stringify(value)}`,
  err: (error) => `Could not parse: ${error.message}`,
});

Choose your path

One contract for people and tools

Every page is also emitted as clean Markdown. The site publishes /llms.txt, /llms-full.txt, page-level .md mirrors, searchable headings, and literal API names. Humans get navigation and examples; coding agents get the same technical contract without scraping presentation markup.

Was this page helpful?