Generic Result/Either Types
What you'll learn: How to model success and failure scenarios using generic types where both the success value and the error are type-safe.
The Problem with Traditional Error Handling
In JavaScript, we typically use try/catch blocks or null checks, which don't give us type safety. When a function might fail, we often return null or throw exceptions, losing information about what went wrong in a type-safe way.
Result Types: A Type-Safe Alternative
A Result (also called Either) is a generic type that represents an operation that could succeed with a value or fail with an error. Both outcomes are explicitly typed:
type Result<T, E> =
| { success: true; value: T }
| { success: false; error: E };
Here, T is your success type and E is your error type. Think of it like a box that either contains what you wanted (T) or an explanation of what went wrong (E).
Using Result Types
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: number
} else {
console.log(result.error); // TypeScript knows: string
}
The discriminated union forces you to check which outcome occurred before accessing the value or error, eliminating runtime surprises.
Why Generics Matter Here
Without generics, you'd need a separate NumberResult, StringResult, etc. With Result<T, E>, one type works for any success/error combination—database queries returning Result<User, DbError>, HTTP calls returning Result<Response, NetworkError>, and so on.
Key Takeaway: Generic Result/Either types let you model fallible operations with full type safety for both success values and errors, making error handling explicit and predictable.