How do you write a generic Result<T, E> discriminated union type for functional-style error handling, and why is it preferred over throwing exceptions in some codebases?
Short answer
Define a generic union of Ok and Err variants with a common discriminant; unlike throw, which is invisible in a function's type signature, a Result return type makes the possibility of failure explicit and forces callers to handle it via the type system rather than relying on…
Advertisement
AModel answer
Define a generic union of Ok<T> and Err<E> variants with a common discriminant; unlike throw, which is invisible in a function's type signature, a Result<T, E> return type makes the possibility of failure explicit and forces callers to handle it via the type system rather than relying on documentation or try/catch discipline.
type Result<T, E = Error> =
| { ok: true; value: T }
| { ok: false; error: E };
function parseNumber(input: string): Result<number, string> {
const n = Number(input);
return isNaN(n) ? { ok: false, error: 'Invalid number' } : { ok: true, value: n };
}Real-world example
Making error handling explicit and type-checked in a validation or parsing layer, rather than relying on undocumented thrown exceptions.
Likely follow-ups
- What are the trade-offs of Result<T,E> versus exceptions for deeply nested call chains?
Related topics