Result Types with Discriminated Unions
What you'll learn: How to model operations that can succeed or fail using discriminated unions to safely handle both outcomes.
The Problem: Handling Success and Failure
Many operations can either succeed (returning data) or fail (returning an error). Without TypeScript, developers often mix return types or throw exceptions, making it unclear what to expect. Result types make success and failure explicit and type-safe.
The Result Pattern
A result type uses discriminated unions to represent two distinct outcomes:
type Result<T> =
| { status: 'ok'; data: T }
| { status: 'error'; error: string };
The status property is your discriminant — TypeScript uses it to narrow which branch you're in.
Why This Works Beautifully
When you narrow on status, TypeScript knows exactly which properties exist:
function divide(a: number, b: number): Result<number> {
if (b === 0) {
return { status: 'error', error: 'Cannot divide by zero' };
}
return { status: 'ok', data: a / b };
}
const result = divide(10, 2);
if (result.status === 'ok') {
console.log(result.data); // TypeScript knows .data exists
} else {
console.log(result.error); // TypeScript knows .error exists
}
No exceptions thrown, no null checks — just exhaustive handling of both cases.
Real-World Use Cases
This pattern shines when fetching data, parsing user input, or validating configuration. You force callers to handle failure, preventing forgotten error cases.
Key Takeaway: Result types with discriminated unions turn success and failure into explicit, type-safe values, eliminating ambiguity and ensuring all outcomes are handled.