Skip to main content

Overview

The Result<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).
Source: result.ts:62 This type is inspired by Rust’s Result type and provides a type-safe way to handle errors without throwing exceptions.

The Two Variants

Ok Variant

The Ok variant represents a successful computation. It wraps a value of type T.
Source: result.ts:312-417 Creating an Ok value:

Err Variant

The Err variant represents a failed computation. It wraps an error value of type E.
Source: result.ts:419-521 Creating an Err value:

Type Safety Benefits

1. Explicit Error Handling

With Result, errors are part of the type signature. This forces you to handle errors explicitly:

2. Type Narrowing

The isOk() 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

Visual Representation

Pattern: Railway-Oriented Programming

The Result type enables “railway-oriented programming” where your program flows on two tracks:
Think of Result as a railway switch: operations on the “Ok track” continue the happy path, while operations on the “Err track” bypass remaining operations and carry the error forward.

Common Patterns

Pattern 1: Transform Success Values

Use map to transform the success value:

Pattern 2: Chain Fallible Operations

Use andThen when the next operation might also fail:

Pattern 3: Error Recovery

Use orElse to recover from errors:

Pattern 4: Extract Values Safely

Use unwrapOr to provide a default value:
Avoid using _unsafeUnwrap() outside of tests. It throws an exception if the Result is an Err, defeating the purpose of type-safe error handling.

Type Signatures from Source

Here are the key type signatures from the implementation:
Source: result.ts:134-310

Next Steps

ResultAsync Type

Learn about handling asynchronous operations with ResultAsync

Error Handling Philosophy

Understand the philosophy behind encoding errors in types