Skip to content

Yakiyo/result_rs

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

37 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

result-rs

Rust's Result enum ported to Typescript/Javascript

Installation

Import the module to your code:

import { Result } from 'https://deno.land/x/result_rs/mod.ts';

It is also published as a npm module as result_rs.

$ npm i result_rs
# or using pnpm
$ pnpm add result_rs
# or yarn
$ yarn add result_rs

Then you can import it in your code:

// Commonjs require
const { Result } = require('result_rs');
// ES Module import
import { Result } from 'result_rs';

Usage

Use the Result.from method to create a new instance of Result

const result = Result.from(someFunctionThatThrows);

result.is_ok(); // Returns false if function throwed an error

The package also exports two utility functions Ok and Err that are useful to create Ok or Err values from simple values instead of a function

import { Err, Ok } from 'https://deno.land/x/result_rs/mod.ts';

const ok = Ok('Hello World');

ok.is_ok(); // true;
ok.unwrap(); // 'Hello World'

const err = Err('Error value');
err.is_er(); // true;
err.unwrap(); // throws an error

Passing async functions to the Result.from method are handled like synchronous functions. If you want to resolve the internal value's promise, you can use the Result.sync method on any instance to resolve the promise internally.

const result = Result.from(async () => 'Hello World');
result.unwrap(); // Promise<string>

await result.sync();
result.unwrap(); // 'Hello World'

Documentation of all methods is available here.

Author

result-rs © Yakiyo. Authored and maintained by Yakiyo.

Released under MIT License