A vanilla module implementing the Result pattern to make the error handling more explicit
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.
1️⃣ Install the library:
``bash`Npm
npm install @open-vanilla/resultPnpm
pnpm add @open-vanilla/resultYarn
yarn add @open-vanilla/result
2️⃣ Once you're done, you can play with the API:
`ts
import { success, failure } from "@open-vanilla/result";
import type { Result } from "@open-vanilla/result";
const createPassword = (input: string): Result
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._
We're open to new contributions, you can find more details here.