Skip to main content

Creating Results

NeverThrow provides two core types for encoding success and failure:

Creating Ok Values

Use ok() to create a successful result:
You can wrap any value, including null and undefined:

Creating Err Values

Use err() to create an error result:

Checking Result State

Type Guards with isOk and isErr

Use isOk() and isErr() to check and narrow the type:

Pattern Matching with match

Handle both cases at once using match():
Both callbacks must return the same type, and match unwraps the Result:

Basic Transformations

Transforming Ok Values with map

map() transforms the value inside an Ok, leaving Err untouched:
If the Result is an Err, map is skipped:

Transforming Err Values with mapErr

mapErr() transforms the error, leaving Ok values untouched:
Useful for adding context to errors:

Extracting Values

Using unwrapOr for Default Values

unwrapOr() extracts the value or returns a default:

Safe Unwrapping in Tests

For testing, use _unsafeUnwrap() and _unsafeUnwrapErr():
Never use _unsafeUnwrap() in production code. These methods throw exceptions if called on the wrong variant and should only be used in test environments.

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 andThen

Async Operations

Work with asynchronous code using ResultAsync