@mypolis.eu/result
v0.5.0
Published
A simple, lightweight, and type-safe way to handle operations that can either succeed with a value or fail with an error, inspired by Rust's Result type. This package provides a `Result<T, E>` type and utility functions to work with it effectively in Type
Downloads
149
Readme
@mypolis.eu/result
A simple, lightweight, and type-safe way to handle operations that can either
succeed with a value or fail with an error, inspired by Rust's Result type.
This package provides a Result<T, E> type and utility functions to work with it
effectively in TypeScript projects.
Features
Type Safety: Leverages TypeScript generics to ensure that success values and errors are handled correctly.
Explicit Error Handling: Makes error handling more explicit and encourages a functional approach.
Simple API: Includes functions like ok, err, wrap, wrapAsync, unwrap, map, mapErr, and match for ergonomic use.
Zero Dependencies: Lightweight and adds no extra dependencies to your project.
Installation
You can install the package using npm, yarn, or pnpm:
npm install @mypolis.eu/resultUsage
First, import the necessary functions and types from the package:
import { Result, ok, err, wrap, wrapAsync, unwrap, map, mapErr, match } from '@mypolis.eu/result';
// Creating Results
// Use ok(value) for successful outcomes and err(error) for failures.
function divide(a: number, b: number): Result<number, string> {
if (b === 0) {
return err("Division by zero is not allowed.");
}
return ok(a / b);
}
const successfulDivision = divide(10, 2); // { ok: true, value: 5, error: null }
const failedDivision = divide(10, 0); // { ok: false, value: null, error: "Division by zero is not allowed." }Building
To build the package from source:
pnpm run buildThis will compile the TypeScript code from src to JavaScript in the dist directory and generate type declarations.
Contributing
Contributions are welcome! Please feel free to submit issues and pull requests. For major changes, please open an issue first to discuss what you would like to change.
License
This project is licensed under the MIT License - see the LICENSE file for details
