Skip to content

Result Type

In one line

Result<T, E> is a union of Ok<T> or Err<E> — explicit error handling without try/catch, inspired by Rust.

In simple words

A Result type is a discriminated union that represents either a successful value or an error. Instead of throwing exceptions, functions return a Result, and the caller must handle both cases.

type Result<T, E> = { ok: true; value: T } | { ok: false; error: E }

Benefits:

  1. Explicit error handling — the type system forces you to check for errors
  2. No forgotten try/catch — impossible to ignore errors
  3. Composable — chain operations with map/andThen
  4. No exception overhead — errors are values, not stack-unwinding throws

Inspired by Rust's Result and Haskell's Either. Popular in functional TypeScript libraries like neverthrow, fp-ts.

Example

typescript
type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };

function divide(a: number, b: number): Result<number, string> {
  if (b === 0) return { ok: false, error: "Division by zero" };
  return { ok: true, value: a / b };
}

const result = divide(10, 2);
if (result.ok) {
  console.log(result.value); // 5 — TypeScript knows value exists
} else {
  console.log(result.error); // TypeScript knows error exists
}

// Can't access result.value without checking result.ok first!

Result forces you to check .ok before accessing .value or .error. The discriminated union ensures type safety — no forgotten error handling.

Common confusions

  • Confused with: try/catch

    The difference: try/catch uses exceptions — errors can be thrown anywhere and forgotten. Result type returns errors as values — the type system forces you to handle both success and error. Result is more explicit and composable; try/catch is more familiar and built-in.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary