(For a list of methods available on Result<T, E>, see ResultMethods)
Overview
A Result<T, E> is a value that represents either a successful computation (Ok<T>) or an error (Err<E>).
It's similar to try/catch blocks, but provides a more functional approach to handling errors and
composing operations that might fail.
To create a Result representing a successful computation of type T, use the Ok function.
For example: const result = Ok(value). If you want to create a Result representing an error of
type E, use Err. For example: const error = Err(new Error("Something went wrong")).
To get the successful value, call unwrap() on the Result. If the result is Err, then unwrap()
will throw the error; thus, it's important to check if a result is Ok or Err before accessing
the value, or use a method that provides a default value in case of Err, like unwrapOr(defaultValue).
Result provides several methods for transforming results and handling errors in a clean, functional way.
By using these methods, we can avoid many try/catch blocks and make our error handling more explicit.
Examples
For example, here's a typical example using traditional error handling:
Overview
A
Result<T, E>is a value that represents either a successful computation (Ok<T>) or an error (Err<E>). It's similar to try/catch blocks, but provides a more functional approach to handling errors and composing operations that might fail.To create a
Resultrepresenting a successful computation of typeT, use theOkfunction. For example:const result = Ok(value). If you want to create aResultrepresenting an error of typeE, useErr. For example:const error = Err(new Error("Something went wrong")).To get the successful value, call
unwrap()on theResult. If the result isErr, thenunwrap()will throw the error; thus, it's important to check if a result isOkorErrbefore accessing the value, or use a method that provides a default value in case ofErr, likeunwrapOr(defaultValue).Resultprovides several methods for transforming results and handling errors in a clean, functional way. By using these methods, we can avoid many try/catch blocks and make our error handling more explicit.Examples
For example, here's a typical example using traditional error handling:
Here's the same example using
Result:You can convert functions that might throw into
Result-returning functions using the built-inOk.try()method:For async functions, you can convert Promises to Results using
Ok.from():And convert Results back to Promises using
toPromise():These methods make it easy to work with existing APIs that throw errors or return Promises while maintaining the benefits of the
Resulttype.Resultis particularly useful when you need to: