TypeScript

Result / Either Type

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Encode "this might fail" in the type signature instead of throwing. Force the caller to handle both branches at compile time. Better than try/catch for foreseeable failures.
TypeScript
Raw
type Ok<T>  = { ok: true;  value: T };
type Err<E> = { ok: false; error: E };
type Result<T, E = Error> = Ok<T> | Err<E>;

const ok  = <T>(value: T): Ok<T>  => ({ ok: true,  value });
const err = <E>(error: E): Err<E> => ({ ok: false, error });

function parseJson<T>(s: string): Result<T, SyntaxError> {
  try { return ok(JSON.parse(s) as T); }
  catch (e) { return err(e as SyntaxError); }
}

const r = parseJson<{ name: string }>('{"name": "Alice"}');
if (r.ok) {
  console.log(r.value.name);    // narrowed to Ok
} else {
  console.error(r.error.message); // narrowed to Err
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.