TypeScript Best Practices
Get the most out of NeverThrow with these TypeScript tips and patterns for better type safety and developer experience.Type Inference Best Practices
Let TypeScript Infer When Possible
In most cases, TypeScript can infer the types of your Results automatically:Avoid Explicit Type Arguments Unless Required
Most methods likemap, andThen, and match infer types correctly:
orElse if you were using explicit types.
Working with Union Types
Distinct Error Types with andThen
Starting in v4.1.0, andThen allows you to return distinct error types that are merged into a union:
Discriminated Unions for Error Handling
Use discriminated unions with error types for exhaustive error handling:Advanced Pattern Matching
Type Narrowing with String Literals
As of v7.1.0,err() infers strings narrowly for easier error tagging:
Generic Result Handlers
Create reusable type-safe handlers:Async Patterns
Combining Sync and Async Results
UseasyncAndThen to transition from Result to ResultAsync:
Working with Promise
Convert promises to ResultAsync safely:Using safeTry with Async Generators
safeTry supports async generator functions for cleaner async error handling:
Handling Multiple Results
Homogeneous Lists
Combine arrays of Results with the same type:Heterogeneous Tuples
Combine Results with different types using tuples:Collecting All Errors
UsecombineWithAllErrors when you need all error values:
Type Guards and Narrowing
Using Type Predicates
Combine Results with custom type guards:Exhaustive Matching
TypeScript ensures exhaustive handling in match callbacks:Performance Tips
Avoid Unnecessary Unwrapping
Stay in the Result context as long as possible:Reuse Error Mappers
Create reusable error transformation functions:Common Patterns
Railway-Oriented Programming
Chain operations on the “happy path”:Side Effects with Type Safety
UseandTee and orTee for side effects: