Result

A TypeScript result type taking cues from Rust's Result and Haskell's Eithe...

README

@badrap/result


A TypeScript result type taking cues from Rust's Result and Haskell's Either types. It's goals are:

- Small, idiomatic API surface: Mix and match parts from Rust's Result and Haskell's Either types, but modify them to make the experience TypeScript-y (TypeScriptic? TypeScriptalicious?). Of course this is pretty subjective.
- Coding errors should throw: While Result#map and Result#chain together somewhat resemble Promise#then but differ in that they don't implicitly wrap errors thrown in callbacks.
- Be ergonomic but safe: Leverage TypeScript's type inference to make common cases simple while keeping type safety. This also helps to get a nice editor experience in e.g. Visual Studio Code.

Installation


  1. ```sh
  2. $ npm i @badrap/result
  3. ```

Usage


  1. ```ts
  2. import { Result } from "@badrap/result";
  3. ```

API


**Result** is a type that wraps either a value that is the result of a succesful computation and of type **T**, or an error of type **E** denoting a failed computation.

The type is actually an union of two types: **Result.Ok** that wraps a success value and **Result.Err** that wraps an error.

Result.ok / Result.err


Result.ok returns a new Result.Ok wrapping the given value, while Result.err returns a new Result.Err wrapping the given error.

  1. ```ts
  2. const res = Result.ok(1);
  3. res.isOk; // true

  4. const res = Result.err(new Error());
  5. res.isOk; // false

  6. const res = Result.err(); // functionally equal to Result.err(new Error())
  7. res.isOk; // false
  8. ```

Result.Ok has an additional property value containing the wrapped value. Similarly, Result.Err has the property error containing the wrapped error. They can be accessed after asserting to TypeScript's type checker that it's safe to do so. The isErr and isOk properties (see below) are handy for this.

  1. ```ts
  2. const res = Math.random() < 0.5 ? Result.ok(1) : Result.err(new Error("oh no"));

  3. if (res.isErr) {
  4.   // TypeScript now knows that res is a Result.Err, and we can access res.error
  5.   res.error; // Error("oh no")
  6. }

  7. if (res.isOk) {
  8.   // TypeScript now knows that res is a Result.Ok, and we can access res.value
  9.   res.value; // 1
  10. }
  11. ```

Result#isOk / Result#isErr


Result#isOk and Result#isErr are complementary readonly properties. isOk is true for Result.Ok and false for Result.Err.

  1. ```ts
  2. const ok = Result.ok(1);
  3. ok.isOk; // true

  4. const err = Result.err(new Error());
  5. err.isOk; // false
  6. ```

isErr is the inverse of isOk: false for Result.Ok and true for Result.Err.

  1. ```ts
  2. const ok = Result.ok(1);
  3. ok.isErr; // false

  4. const err = Result.err(new Error());
  5. err.isErr; // true
  6. ```

Result#unwrap


Return the wrapped value for Result.Ok and throw the wrapped error for Result.Err.
This can be modified for providing functions to map the value and error to some value.

  1. ```ts
  2. const ok = Result.ok(1);
  3. const err = Result.err(new Error("oh no"));

  4. ok.unwrap(); // 1
  5. err.unwrap(); // throws Error("oh no")

  6. ok.unwrap((value) => value + 1); // 2
  7. err.unwrap((value) => value + 2); // throws Error("oh no")

  8. ok.unwrap(
  9.   (value) => value + 1,
  10.   (error) => 0
  11. ); // 2
  12. err.unwrap(
  13.   (value) => value + 2,
  14.   (error) => 0
  15. ); // 0
  16. ```

As a small extra convenience the result types from the callbacks don't have to be the same.
Here's an example Koa.js handler demonstrating this, using an imaginary
validate function that returns a Result:

  1. ```ts
  2. app.use(async ctx =>
  3.   await validate(ctx.request.body).unwrap(
  4.     async (value: any) => {
  5.       ...
  6.     },
  7.     error => {
  8.       ctx.status = 422;
  9.       ctx.body = {
  10.         message: "validation failed"
  11.       };
  12.     }
  13.   )
  14. );
  15. ```

Result#map


Return a new Result where the given function/functions have been applied
to the wrapped value and error.

  1. ```ts
  2. const ok = Result.ok(1);
  3. const err = Result.err(new Error("oh no"));

  4. ok.map((value) => value + 1).unwrap(); // 2
  5. err.map((value) => value + 1).unwrap(); // throws Error("oh no")

  6. ok.map(
  7.   (value) => value + 1,
  8.   (error) => new Error("mapped")
  9. ).unwrap(); // 2
  10. err
  11.   .map(
  12.     (value) => value + 1,
  13.     (error) => new Error("mapped")
  14.   )
  15.   .unwrap(); // throws Error("mapped")
  16. ```

Result#chain


  1. ```ts
  2. const ok = Result.ok(1);
  3. const err = Result.err(new Error("oh no"));

  4. ok.chain((value) => Result.ok(value + 1)).unwrap(); // 2
  5. err.chain((value) => Result.ok(value + 1)).unwrap(); // throws Error("oh no")

  6. ok.chain(
  7.   (value) => Result.ok(value + 1),
  8.   (error) => Result.ok(0)
  9. ).unwrap(); // 2
  10. err
  11.   .chain(
  12.     (value) => Result.ok(value + 1),
  13.     (error) => Result.ok(0)
  14.   )
  15.   .unwrap(); // 0
  16. ```

Result.all


Return a new Result where the wrapped value is the
collection of the wrapped values of the input array.

  1. ```ts
  2. Result.all([Result.ok(1), Result.ok("test")]).unwrap(); // [1, "test"]
  3. ```

If any of the input results wraps an error then that result is returned as-is.

  1. ```ts
  2. Result.all([Result.ok(1), Result.err(new Error("oh no"))]).unwrap(); // throws Error("oh no")
  3. ```

Non-array objects can also be given as arguments. In that case the wrapped
output value is also an object.

  1. ```ts
  2. Result.all({
  3.   x: Result.ok(1),
  4.   y: Result.ok("test"),
  5. }).unwrap(); // { x: 1, y: "test" }
  6. ```

License


This library is licensed under the MIT license. See LICENSE.