@openally/result
TypeScript icon, indicating that this package has built-in type declarations

1.2.1 • Public • Published

Result

[WIP] Another Rust's Result implementation (inspired by ts-results)

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

Readme

Keywords

none

Package Sidebar

Install

npm i @openally/result

Weekly Downloads

328

Version

1.2.1

License

MIT

Unpacked Size

14.6 kB

Total Files

6

Last publish

Collaborators

  • fraxken