Skip to content

yifanwww/rustlike-result

Repository files navigation

Rust-Like Result

Rust-like Result and ResultAsync for JavaScript.

Result is a type that represents either success (Ok) or failure (Err), ResultAsync is the asynchronous version of Result.

Table Of Contents

Installation

> npm install @rustresult/result
> pnpm install @rustresult/result
> yarn add @rustresult/result

Usage

This package implements a Rust-like Result, nearly all methods are similar to the Rust Result.

const ok = Ok(1);
const err = Err('Some error message');
import fs, { Stats } from 'node:fs/promises';

const result1: Result<Stats, Error> = await fs
    .stat(path)
    .then((value) => Ok(value))
    .catch((err) => Err(err));

const readdir = resultifyAsync<Error>(fs.readdir);
const result2 = readdir(path, { withFileTypes: true });
//    ^ ResultAsync<Dirent[], Error>

API Documentation

Rust-Like Result Core

Check out @rustresult/result for the core of Rust-like Result

JSON Serialization & Deserialization

Third-Party Library Helpers

Result is not a built-in feature in JavaScript. You will definitely feel that it's hard to make Result work with third-party libraries. There are also some helpers for you.

About Rust Option

This project doesn't implement Rust-like Option. Handling undefined/null is not as hard as it was a few years ago, because right now we already have these proposals to help handle it:

License

The rustlike-result project is available as open source under the terms of the MIT license.

About

Rust-like Result for Javascript

Resources

License

Stars

Watchers

Forks

Packages

No packages published