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

0.0.2 • Public • Published

ts-stdlib Result

Version Size Dependencies License

Ensemble of utility for managing executions that might fail

Installation

npm install @ts-stdlib/result

or

yarn add @ts-stdlib/result

Usage

import {runCatching} from "@ts-stdlib/result";

const result = runCatching(() => {
    // do something that might fail
});

if (result.isSuccess) {
    // do something with result.value
}

catching

import {catching} from "@ts-stdlib/result";

const dangerousFn = (name: string) => {
    // do something that might fail
};

const safeFn = catching(dangerousFn);

const result = safeFn("Federico");

getOrDefault and getOrElse

const length = result
    .map((value) => value.length)
    .getOrDefault(0);
const length = result
    .map((value) => value.length)
    .getOrElse(() => 0);

Mix types

const length: number | "N/A" = result
    .map((value) => value.length)
    .getOrDefault("N/A");

recovery

const lengthResult: number = result.recover((e) => {
    if (e instanceof TypeError) {
        return 0;
    }

    if (e instanceof RangeError) {
        return 1;
    }

    return 2;
});

// it's safe to use lengthResult.value here
// becasue we used `recover`
const length: number = lengthResult.value;

or

const fallbackResult = runCatching(() => "javascript");

const result: Result<string> = runCatching(() => "typescript")
    .or(fallbackResult)
    .map((value) => value.toUpperCase());

Package Sidebar

Install

npm i @ts-stdlib/result

Weekly Downloads

1

Version

0.0.2

License

MIT

Unpacked Size

18.8 kB

Total Files

8

Last publish

Collaborators

  • federicopeyrani