1.2.1 • Published 2 months ago

@openally/result v1.2.1

Weekly downloads
-
License
MIT
Repository
-
Last release
2 months ago

Requirements

Getting Started

This package is available in the Node Package Repository and can be easily installed with npm or yarn.

$ npm i @openally/result
# or
$ yarn add @openally/result

Usage example

import fs from "node:fs";
import { Result, Ok, Err } from "@openally/result";

function readFile(path: string): Result<string, "invalid path"> {
  if (existsSync(path)) {
    return Ok(fs.readFileSync(path, "utf8"));
  }

  return Err("invalid path");
}

const fileContentStr = readFile("test.txt").unwrap();
console.log(fileContentStr);

API

unwrap()

Unwrap value (throw if error).

Ok(1).unwrap(); // 1
Err("oops").unwrap(); // Error: Tried to unwrap Error: oops

unwrapOr(value)

Unwrap with a default value (if an error is detected).

Ok(1).unwrapOr(5); // 1
Err("oops").unwrapOr(5); // 5

map()

Map for an Ok value.

Ok(1)
  .map((v) => v + 1)
  .unwrap(); // 2

mapErr()

Map for an Error value.

andThen()

Ok(1)
  .andThen((value) => Ok(value + 1))
  .unwrap(); // 2

License

MIT