Course contentsShow
← TypeScript
Lesson 613 of 1,79614. Generics in PracticeFree lesson

Result/Either Type for Error Handling

Create a generic Result<T, E> type that represents success or failure without exceptions.

Result/Either Type for Error Handling

What you'll learn: How to create a generic Result<T, E> type that cleanly represents operations that can succeed with a value or fail with an error — all without throwing exceptions.


The Problem with Exceptions

In traditional error handling, you throw exceptions and hope they're caught. But TypeScript doesn't enforce that you handle them — a function that might throw looks identical to one that never does. This makes errors invisible in your type signatures.

A Result type solves this by making errors explicit and type-safe. Instead of throwing, functions return a Result that's either a success containing your value, or a failure containing your error.


Creating the Generic Result Type

Think of Result<T, E> as a box that contains either a success of type T or an error of type E. We use a discriminated union:

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

The success property is our discriminant — it tells us which variant we have.


Using Result in Practice

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

const result = divide(10, 2);

if (result.success) {
  console.log(result.value); // TypeScript knows 'value' exists here
} else {
  console.log(result.error); // TypeScript knows 'error' exists here
}

Notice how the type system forces you to check for errors before accessing the value. No silent failures, no uncaught exceptions.


The Power of Generic Parameters

  • T: The type of the success value (flexible for any operation)
  • E: The type of the error (could be string, a custom error object, or even another union type)

This pattern is especially powerful when chaining operations or building pipelines where each step might fail.


Key Takeaway: A generic Result<T, E> type makes error handling explicit in your type signatures, forcing callers to acknowledge both success and failure cases without relying on exceptions.