Creating Results
NeverThrow provides two core types for encoding success and failure:Creating Ok Values
Useok() to create a successful result:
null and undefined:
Creating Err Values
Useerr() to create an error result:
Checking Result State
Type Guards with isOk and isErr
UseisOk() and isErr() to check and narrow the type:
Pattern Matching with match
Handle both cases at once usingmatch():
match unwraps the Result:
Basic Transformations
Transforming Ok Values with map
map() transforms the value inside an Ok, leaving Err untouched:
Err, map is skipped:
Transforming Err Values with mapErr
mapErr() transforms the error, leaving Ok values untouched:
Extracting Values
Using unwrapOr for Default Values
unwrapOr() extracts the value or returns a default:
- Real-World Example
- With Error Recovery
Safe Unwrapping in Tests
For testing, use_unsafeUnwrap() and _unsafeUnwrapErr():
Comparing Results
Result instances are comparable for testing:Complete Example: Form Validation
Here’s a real-world example combining basic operations:Next Steps
Chaining Operations
Learn how to compose multiple operations with
andThenAsync Operations
Work with asynchronous code using
ResultAsync