Skip to content
Tutorials Center
My learning

Topics

Lesson 56 of 96 ยท Async and Errors

Result and Either Types for Errors

Build a typed Result and Either in TypeScript - ok and err helpers, map, andThen, match, wrapping throwing code, async results, collecting many results and when to use them.

Exceptions are the default way to report failure in JavaScript, but they have a weakness in a typed language: they are invisible. The signature parseConfig(text: string): Config does not say that it can throw, so nothing makes the caller think about the failure. A Result type moves the failure into the return type. A function that can fail returns either a success value or an error value, and the compiler makes the caller look at which one they got.

Error Handling introduced the pattern with a tiny Result and a single example. This lesson builds the whole toolkit: constructors, transformations (map, andThen), a safe wrapper for throwing code, async results, combining many results, and the closely related Either type. It relies on discriminated unions and generics. All the code here is plain TypeScript, with no library.

The Result type

A Result<T, E> is a union of two object types, told apart by a literal ok property:

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

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

The small constructors return the specific Ok<T> or Err<E> type, not Result. That matters: ok(5) has type Ok<number>, which is assignable to Result<number, AnyError> for any error type, and err('x') is assignable to a Result of any value type. A function returning Result<number, string> can therefore return ok(1) in one branch and return err('bad') in another with no casts.

Because ok is a literal, checking it narrows the union. Inside if (result.ok) the compiler knows about value; in the other branch it knows about error.

Transforming results: map and andThen

Checking result.ok after every call becomes repetitive when several fallible steps follow each other. A few small helper functions fix that. They are the core of the pattern:

  • map transforms the success value and leaves an error untouched.
  • mapErr transforms the error and leaves a success untouched.
  • andThen (also called flatMap or bind) chains a step that itself returns a Result.
  • match handles both cases and produces one value.
TypeScript Result with map, andThen and match

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The first four calls print 50%, "abc" is not a number, 150 is outside 0-100 and total must not be zero, and the last line prints { ok: false, error: 'X' }. Look at the type that andThen returns: Result<U, E | F>. The error type is the union of all the steps' error types, so the compiler knows exactly which failures can come out of the pipeline. That is why the switch over e.kind in match must handle parse, range and divide-by-zero, and why it fails to compile if you forget one. Add a fourth step with a new error kind, and every place that handles the pipeline's errors is flagged until updated.

flowchart LR
    I["input string"] --> P["parseNumber"]
    P -- "Ok" --> R["inRange"]
    P -- "Err parse" --> X["error channel"]
    R -- "Ok" --> D["percentOf"]
    R -- "Err range" --> X
    D -- "Ok" --> OKV["success value"]
    D -- "Err divide-by-zero" --> X

A chain of andThen steps: the first Err skips every later step and arrives as the final error.

Wrapping code that throws

Real APIs throw: JSON.parse, fs.readFileSync, new URL(...), your teammate's helper. The edge of your program is where you convert those exceptions into Results, once, so the rest of the code can stay exception-free.

A generic wrapper keeps that conversion to one place:

TypeScript tryCatch and a typed domain error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output is config: { host: 'db.local', port: 5432 }, then missing: port, then a line that starts with bad json: and the beginning of the JSON parser's message. The toError callback is where you decide how a thrown value (an unknown, as Error Handling explained) becomes one of your own error types. Note how the early return parsed works: inside if (!parsed.ok) the value has the Err<ConfigError> type, which is already a valid Result<Config, ConfigError>.

Async results

An async function that can fail has two failure channels if you are not careful: the Promise can reject (an exception), or it can resolve to an error Result. The rule that keeps this simple is never reject for expected failures. Return a Promise<Result<T, E>> and keep exceptions for bugs.

TypeScript Promise of a Result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

This prints Hello, Ada!, failed: not-found and failed: network. The await expression gives you the Result directly, so there is no try/catch in the caller. If you wrap a Promise that may reject (a fetch call), put the try/catch inside the function that talks to the outside world, as in tryCatch above, and return the Result from there. See Promises and Async for the basics.

Combining many results

Often you have a list of operations and want "all of them succeed, or the first failure". That is all, sometimes called sequence:

TypeScript
function all<T, E>(results: readonly Result<T, E>[]): Result<T[], E> {
  const values: T[] = [];
  for (const r of results) {
    if (!r.ok) {
      return r;
    }
    values.push(r.value);
  }
  return ok(values);
}

const parsed = all(['1', '2', '3'].map(parseNumber));        // Ok with value [1, 2, 3]
const failed = all(['1', 'x', '3'].map(parseNumber));        // Err: { kind: 'parse', input: 'x' }

A variant, partition, collects every success and every failure instead of stopping at the first error, which is the right tool for form validation where you want to show all problems at once. Both are short loops, and typed once they work for any element type.

Either: the general form

Either<L, R> is the same idea without the success and failure meaning. A value is Left or Right. By convention the right side is the "right" (correct) answer and the left holds the error, which is why many libraries (fp-ts, for example) use Either<E, A> for error handling. Where Result names its sides ok and error, Either names them left and right:

TypeScript A neutral Either with fold

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output is cached: 12, loading (miss) and { ok: true, value: 5 } { ok: false, error: 'bad' }. The _tag property name is a convention from functional libraries; any literal discriminant works. In everyday TypeScript, prefer Result when the two sides mean success and failure, because the names ok and error tell the reader what is going on. Use Either when the two sides are just two different outcomes.

Choosing between exceptions and Results

Results are not always better. Choose by what the caller can do:

  • Result for expected failures a caller can act on: validation, "not found", parsing user input, a declined payment, a rate limit.
  • Exceptions for bugs and broken invariants, such as an impossible switch branch, or failures that can only be handled at the top level (log, show an error page).
  • Both at the edges. Convert exceptions from libraries into Results close to the call (tryCatch), and, at the boundary of your program (an HTTP handler, a CLI main), turn the final Result into a response or an exit code.

Libraries such as neverthrow, Effect and fp-ts provide fuller versions, with method chaining (result.map(...).andThen(...)) and extra helpers. The plain functions here are often enough, they add no dependency, and they work well with the typed API client project. One caution: a Result only helps if callers cannot ignore it silently. Turn on the lint rule @typescript-eslint/no-floating-promises for async code so a forgotten await on a Promise<Result> does not slip through.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why do the constructors ok and err return Ok<T> and Err<E> instead of Result<T, E>?

    The narrower return types are assignable to the full union with any error or value type, so a function can return ok in one branch and err in another.
  2. 2. What is the error type of andThen(a, f) where a is Result<A, E1> and f returns Result<B, E2>?

    The chain can fail in either step, so the error is the union of both error types. A switch over it must handle every case.
  3. 3. Where should a thrown exception from JSON.parse be converted into a Result?

    Wrapping the throwing call in one place (tryCatch) keeps the rest of the code exception-free and typed.
  4. 4. An async function returns Promise<Result<User, FetchError>>. How does the caller see a 'not found' failure?

    Expected failures travel as values inside the resolved Result. Rejection is kept for unexpected problems.
  5. 5. When is Either a better name than Result?

    Either is neutral about meaning. Result's ok and error names fit success and failure; Either fits other either-or choices.

Summary

  • A Result<T, E> is a discriminated union of Ok<T> and Err<E> that puts failure into the type, so callers must handle it.
  • Small helpers do the work: map, mapErr, andThen (error types accumulate into a union), match and all.
  • Wrap throwing APIs once with a tryCatch helper and let the rest of the code deal in values.
  • Async functions return Promise<Result<T, E>> for expected failures and reserve rejection for bugs.
  • Either<L, R> is the neutral two-sided form; convert freely between it and Result.
  • Use Results for expected failures and exceptions for bugs, and convert at the edges of the program.

Next: Decorators