Represents the result of a computation that may fail.
Result is a functional approach to error handling that makes success and failure explicit in the type system. Instead of throwing exceptions, operations return a Result that is either Ok (success) or Error (failure).
This pattern forces callers to handle both success and error cases, making error handling more predictable and easier to reason about.
Example 1
Example 1
// Basic usage function divide(a: number, b: number): Result<number> { if (b === 0) { return Result.Error('Cannot divide by zero') } return Result.Ok(a / b) } const result = divide(10, 2) result.matchWith({ Ok: (value) => console.log(`Result: ${value}`), Error: (error) => console.error(`Error: ${error}`) })
Transforms the Ok value using a function that returns a Result (also known as flatMap).
Similar to map, but the handler function returns a Result instead of a plain value. This is useful for chaining operations that may themselves fail, avoiding nested Results.
Gets the Ok value or returns a default value if this is an Error.
This provides a simple way to extract a value from a Result with a fallback, without needing to use pattern matching.
Transforms the Ok value using the provided function.
If the Result is Ok, applies the handler to the value and returns a new Ok Result. If the Result is Error, returns the Error unchanged without calling the handler.
This allows you to chain transformations on successful values while automatically propagating errors.
Replaces the error with a new error message if this Result is an Error.
This is useful for providing more context to errors, normalizing error messages, or hiding implementation details from callers.
matchWith<OkReturnType,ErrorReturnType,>(pattern: { Ok: (value: Type) => OkReturnType; Error: (error: ResultError) => ErrorReturnType; }): OkReturnType | ErrorReturnType
Pattern matches on the Result, executing different handlers for Ok and Error cases.
This is the primary way to extract values from a Result. Both cases must be handled, ensuring exhaustive error handling at compile time.
Extracts the value or error from the Result.
This collapses the Result into a single type that could be either the success value or the error. Use this when you need to handle both cases the same way, or when the value and error types are compatible.
orElse<HandlerType>(handler: (value: Result<Type>) => Result<HandlerType>): Result<Type> | Result<HandlerType>
Returns this Result if it's Ok, otherwise calls the handler with the Error.
This allows you to provide an alternative Result when an error occurs, potentially recovering from specific errors or trying alternative approaches.
Wraps a Promise into a Result, converting rejections to Error results.
This allows you to work with async operations using the Result pattern, avoiding the need for try/catch blocks.
HasInstance<Type>(value: unknown): value is Result<Type>
Type guard to check if a value is a Result instance.