Skip to content

Errors and Result

Goal: Propagate failures explicitly through call stacks.

Unexpected bugs may still throw at runtime, but expected failures belong in Result.

Example

type Result<T, E> = Ok(T) | Err(E)

function step1(): Result<number, string> {
  return Ok(2)
}

function step2(n: number): Result<number, string> {
  if (n < 0) return Err("negative")
  return Ok(n * 10)
}

function pipeline(): Result<number, string> {
  const a: Result<number, string> = step1()
  return match a {
    Ok(n) => step2(n),
    Err(e) => Err(e),
  }
}

Open in playground

Key takeaways

  • Callers must handle Err — the type system enforces it.
  • Combine steps with match or helper functions.
  • See migration guide.

Next: Iterators and for...of

Documentation