Overview
TheResult<T, E> type is the foundation of NeverThrow. It represents a computation that can either succeed with a value of type T (wrapped in Ok) or fail with an error of type E (wrapped in Err).
Result type and provides a type-safe way to handle errors without throwing exceptions.
The Two Variants
Ok Variant
TheOk variant represents a successful computation. It wraps a value of type T.
Err Variant
TheErr variant represents a failed computation. It wraps an error value of type E.
Type Safety Benefits
1. Explicit Error Handling
WithResult, errors are part of the type signature. This forces you to handle errors explicitly:
2. Type Narrowing
TheisOk() and isErr() methods act as type guards, narrowing the type within conditional blocks:
3. Composable Error Types
Results can be chained, and TypeScript tracks the union of all possible error types:TypeScript automatically infers and combines error types when chaining operations, ensuring you never miss a possible error case.
4. No Silent Failures
Unlike exceptions that can be thrown and forgotten,Result forces you to acknowledge the possibility of failure:
Comparison: Exceptions vs Result
- With Exceptions
- With Result
Visual Representation
Pattern: Railway-Oriented Programming
TheResult type enables “railway-oriented programming” where your program flows on two tracks:
Common Patterns
Pattern 1: Transform Success Values
Usemap to transform the success value:
Pattern 2: Chain Fallible Operations
UseandThen when the next operation might also fail:
Pattern 3: Error Recovery
UseorElse to recover from errors:
Pattern 4: Extract Values Safely
UseunwrapOr to provide a default value:
Type Signatures from Source
Here are the key type signatures from the implementation:Next Steps
ResultAsync Type
Learn about handling asynchronous operations with ResultAsync
Error Handling Philosophy
Understand the philosophy behind encoding errors in types