Introduction
Handling results from an operation is an essential aspect of software development, and doing it gracefully can often be challenging. we have a powerful tool at our disposal — the ResultJS Package. This Package simplifies error and success value handling, making your code more readable and maintainable. In this article, we’ll embark on a journey to discover the capabilities and advantages of the ResultJS
Package.
Installation
npm i @sylvainka12/resultjs
bun add @sylvainka12/resultjs
Understanding the Basics
Before we dive deep, let’s grasp the fundamental concepts.
At its core, the Result Package revolves around two primary classes:
Ok<T>
: Represents the 'Ok' state and stores a value of type T.
Err<E>
: Represents the 'Err' state and stores an error of type E.
These classes are encapsulated in a Result<T, E>
type provides a structured way to handle both success and error states.
Creating Result Objects
Let’s create some Result objects:
import { Ok, Err, Result } from '@sylvainka12/resultjs';
const successResult: Result<number, string> = new Ok(42);
const errorResult: Result<number, string> = new Err("Something went wrong");
Checking the State
You can easily check the state of a Result using the isOK()
and isErr()
methods:
if (successResult.isOK()) {
// Handle the 'Ok' state
} else {
// Handle the 'Err' state
}
Accessing Values
To access the values inside Ok
and Err
objects, use the ok()
and err()
methods:
const value = successResult.ok(); // Returns 42
const error = errorResult.err(); // Returns "Something went wrong"
Unwrapping Results
The library also provides unwrap and unwrapErr methods for extracting the value or error safely. These methods throw an UnwrapError if used incorrectly.
try {
const value = successResult.unwrap();
// Use the 'value' here
} catch (error) {
// Handle the 'UnwrapError' if the result is in the 'Err' state
}
Matching Results
A powerful feature is the matchResult
function, which simplifies working with Result objects:
const { ok, err } = matchResult(successResult);
if (ok !== null) {
// Handle the 'Ok' value
} else {
// Handle the 'Err' value
}
Conclusion
The ResultJS Package offers a structured and type-safe way to handle errors and success in your TypeScript projects. By embracing its capabilities, you can create more reliable and maintainable code.
To learn more check the package on Github.
ResultJS package is inspired by Rust Result.
Top comments (0)