- What does it do ?
- Compatibility
- Dependencies
- Installation
- How to use
- Incorrect usages
- Credits
- License
Provide a simple implementation of the Operation Result Pattern for TypeScript to avoid boilerplate code.
TypeScript | EcmaScript |
---|---|
>= 2.8.0 | >= ES2015 |
This package is dependencies-free.
Nothing more than :
npm i -S @sefr/result
✅ 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...
}
❌ 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();
}
- Developed with the awesome TypeScript
- Tested with Mocha and Chai
- Code style enforced with ESLint and TypeScript-ESLint
This software is available under the MIT License. See the LICENSE file for more informations.