Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@aurelle/result

Package Overview
Dependencies
Maintainers
1
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@aurelle/result

Simple error handling library inspired by Rust's Result type

  • 1.0.1
  • npm
  • Socket score

Version published
Weekly downloads
2
Maintainers
1
Weekly downloads
 
Created
Source

A Typescript error handling library inspired by Rust's Result type.

There is a lot of those already, but this one aims to be simple and doesn't attempt to turn Typescript into a functional programming language.

I originally wrote this because I find error handling in Typescript absolutely terrible. Wrapping everything in try/catch blocks really isn't my thing.

If you plan to use this, I recommend you simply copy src/index.ts into your project instead of installing this package, given how small it is.

Usage

Writing a function that returns a Result

import { Result, Ok, Err } from '@aurelle/result';

const divide = (a: number, b: number): Result<number, Error> {
    if (b === 0) {
        return Err(new Error('Division by zero'));
    }

    return Ok(a / b);
}

Using a Result

Checking for error on the result
const result = divide(10, 2);

if (result.err) {
    // handle error
    return ;
}

// work with result
console.log(result.val);
Using a tuple
const [divided, divisionErr] = divide(10, 2).split();

if (divisionErr) {
    // handle error
    return ;
}

// work with result
console.log(divided);
Ignoring the error
// throws if there is an error
const divided = divide(10, 2).unwrap();

console.log(divided);

Working with existing functions

It is possible to turn any existing function into a function that returns a Result by using the resultify utility:

import { readFileSync } from 'fs';
import { resultify } from '@aurelle/result';

const rfs = resultify(readFileSync);
const file = rfs('file.txt', 'utf8'); // Result<string, Error>

Note that resultify also works with async functions. It will return a function that returns a Promise<Result<T, E>>.

FAQs

Package last updated on 06 Jun 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc