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

1.0.11 • Public • Published

@sefr/result ✨

What does it do ? 💡

Provide a simple implementation of the Operation Result Pattern for TypeScript to avoid boilerplate code.

Compatibility 🔧

TypeScript EcmaScript
>= 2.8.0 >= ES2015

Dependencies 🎱

This package is dependencies-free.

Installation 💾

Nothing more than :

npm i -S @sefr/result

How to use 📚

✅ Returning a success without content :

import { Result } from "@sefr/result";

function doSomething(...args: Array<unknown>): Result<Error> {
    return Result.ok();
}

const toto: Result<Error> = doSomething();

if (toto.isFailure) {
	// do something...
}

✅ Returning a success with a string content :

import { Result } from "@sefr/result";

function doSomething(...args: Array<unknown>): Result<string | Error> {
	return Result.ok("Operation successful !");
}

const toto: Result<string | Error> = doSomething();

if (toto.isFailure) {
	// do something...
} else {
	const titi = toto.value; // "Operation successful"
}

✅ Returning a failure with some custom error :

import { Result } from "@sefr/result";

class SomeCustomError extends Error {
	constructor(public readonly someMoreInformation: Record<string, string>, message: string) {
		super(message);
	}
}

function doSomething(...args: Array<unknown>): Result<string | SomeCustomError> {
	return Result.failure(new SomeCustomError(
		{ id: "5", someMoreInfo: "stuff & co..." },
        "Oops! Something went wrong !"
    ));
}

const toto: Result<string | SomeCustomError> = doSomething();

if (toto.isFailure) {
	const titi = toto.value; // SomeCustomError
	// do something...
}

Incorrect usages ❌

❌ Returning an error as successful operation is not allowed, TypeScript will not allow it :

import { Result } from "@sefr/result";

function doSomething(...args: Array<unknown>): Result<string | Error> {
	return Result.ok(new Error("Operation successfull !"));
}

❌ Returning a failure without any reason (understand Error), TypeScript will also fail on build :

import { Result } from "@sefr/result";

function doSomething(...args: Array<unknown>): Result<string | Error> {
	return Result.failure();
}

Credits 📎

License 📜

This software is available under the MIT License. See the LICENSE file for more informations.

⬆️ Go back to top

Package Sidebar

Install

npm i @sefr/result

Weekly Downloads

13

Version

1.0.11

License

MIT

Unpacked Size

16.3 kB

Total Files

15

Last publish

Collaborators

  • sefr