@open-vanilla/result
v3.0.0
Published
A vanilla module implementing the Result pattern to make the error handling more explicit
Downloads
18
Readme
✨ Features
TypeScript's implementation for the Result pattern inspired by the Rust and Swift primitive. The Result pattern is an implementation variant of Either pattern well-known in some functional programming languages.
In contrast to traditional exception handling, the Result pattern:
- Makes the control flow and error handling more explicit (the developer has to handle both scenarios (failure and success)).
- Add less performance overhead as returning a value is generally faster than throwing an exception.
🚀 Quickstart
1️⃣ Install the library:
# Npm
npm install @open-vanilla/result
# Pnpm
pnpm add @open-vanilla/result
# Yarn
yarn add @open-vanilla/result2️⃣ Once you're done, you can play with the API:
import { success, failure } from "@open-vanilla/result";
import type { Result } from "@open-vanilla/result";
const createPassword = (input: string): Result<string> => {
if (input.length < 12) {
return failure(
new Error("The password must be longer than 12 characters"),
);
}
return success(input);
};
const password = createPassword("hello1234");
if (password.type === "failure") {
// Password failure case logic.
console.error("Failure case", password.payload);
} else {
// Password success case logic.
console.log("Success case", password.payload);
}You can check the examples folder for more use cases.
✍️ Contribution
We're open to new contributions, you can find more details here.
