Type-safe result pattern
Error handling in TypeScript through a discriminated union instead of a thrown exception.
- #typescript
- #patterns
- #error-handling
A TypeScript signature says nothing about what a function throws, so a caller can skip the failure case and find out at runtime.
Result<T, E> models an operation that either succeeds with a value T or fails with an error E, as a discriminated union.
Motivation
When a function returns Result<T, E>, TypeScript makes the caller check .ok before reading .value or .error:
Implementation
The full implementation is in result.ts:
Related entries
- useDebounce hook. Debounce an async call that returns a
Result. - Accessible command menu. Runs a command and recovers from a typed error.
Files in this entry
Saved beside the document, and served as-is.
Related entries
OneOf: exclusive unions
A union in TypeScript does not forbid mixing its members. A mapped utility type makes the members mutually exclusive.
Error boundaries
Keep a render-time failure inside one subtree, and recover from it without a full page reload.
Compound components
Expose a component's internals as named subcomponents that share state through a private context.