Package Exports
- @consolidados/results
- @consolidados/results/globals
- @consolidados/results/helpers
- @consolidados/results/option
- @consolidados/results/result
Readme
ResulTS
This package provides robust implementations of the Result and Option types, inspired by functional programming principles, to handle success/failure scenarios and optional values in your TypeScript backend applications. It also includes helper functions and a match function for convenient usage.
The Result<T, E> type is heavily inspired by Rust's Result and aims to provide a
robust way to handle success and failure scenarios in TypeScript.
The Option<T> type is heavily inspired by Rust's Option and aims to provide a robust way to handle optional values in TypeScript,
avoiding null and undefined issues.
Installation (Global Availability Recommended)
For ease of use, the Ok, Err, Some, None, and match functions can be made globally available in your TypeScript project.
Configure
tsconfig.json:Within the
compilerOptions, add the following to thetypesarray:"types": ["vitest/globals", "@consolidados/results/globals"]
Import in Entry Point (e.g.,
main.tsorindex.ts):Import the entire package in your main application file:
// main.ts import "@consolidados/results";
After this setup, you can use
Ok,Err,Some,None, andmatchdirectly in your code without explicit imports.
Core Concepts
Result<T, E>
The Result<T, E> type represents the outcome of an operation that can either succeed with a value of type T or fail with an error of type E (typically extending Error).
Generic Types:
T: The type of the successful value.E: The type of the error value (should extendError).
Usage Example:
function divide(a: number, b: number): Result<number, Error> {
if (b === 0) {
return Err(new Error("Cannot divide by zero"));
}
return Ok(a / b);
}
const result1 = divide(10, 2);
const result2 = divide(10, 0);
if (result1.isOk()) {
console.log("Result:", result1.unwrap()); // Output: Result: 5
}
if (result2.isErr()) {
console.error("Error:", result2.unwrapErr().message); // Output: Error: Cannot divide by zero
}Ok<T>
Represents a successful result containing a value of type T.
Constructor:
new Ok<T>(value: T)Example:
const successResult: Result<string, Error> = Ok("Operation successful");Err<E extends Error>
Represents a failed result containing an error of type E.
Constructor:
new Err<E>(error: E | string)Example:
const failureResult: Result<number, Error> = Err(new Error("Operation failed"));
const failureResultWithMessage: Result<number, Error> = Err("Something went wrong");Result Methods
isOk(): this is Ok<T>: Checks if the result is a successfulOkvalue.isErr(): this is Err<E>: Checks if the result is a failedErrvalue.unwrap(): T: Extracts the successful value or throws an error if it's anErr.unwrapErr(): E: Extracts the error value or throws an error if it's anOk.map<U>(fn: (value: T) => U): Result<U, E>: Applies a transformation function to the value of anOk.flatMap<U>(fn: (value: T) => Result<U, E>): Result<U, E>: Applies a function that returns aResultto the value of anOk.mapErr<U extends Error>(fn: (err: E) => U): Result<T, U>: Applies a transformation function to the error value of anErr.
Option<T>
The Option<T> type represents an optional value that may or may not exist.
Generic Type:
T: The type of the optional value.
Usage Example:
function findUser(id: number): Option<string> {
if (id === 123) {
return Some("John Doe");
}
return None();
}
const user1 = findUser(123);
const user2 = findUser(456);
if (user1.isSome()) {
console.log("User:", user1.unwrap()); // Output: User: John Doe
}
if (user2.isNone()) {
console.log("User not found"); // Output: User not found
}```
#### `Some<T>`
Represents an `Option` that contains a value of type `T`.
**Constructor:**
```TypeScript
new Some<T>(value: T)Example:
const presentValue: Option<number> = Some(42);None
Represents an Option that does not contain a value.
Example:
const absentValue: Option<string> = None();Option Methods
isSome(): this is Some<T>: Checks if the option contains a value (Some).isNone(): this is None: Checks if the option does not contain a value (None).unwrap(): T: Extracts the value from aSomeor throws an error if it'sNone.map<U>(fn: (value: T) => U): Option<U>: Applies a transformation function to the value of aSome.flatMap<U>(fn: (value: T) => Option<U>): Option<U>: Applies a function that returns anOptionto the value of aSome.unwrapOr(defaultValue: T): T: Extracts the value from aSomeor returns a default value if it'sNone.
match Function
The match function provides a concise way to handle different cases for both Result and Option types.
Usage with Result:
const result: Result<string, Error> = Ok("Success");
const optionResult: Option<string> = match(result, {
Ok: (value) => Some(value),
Err: (error) => None(),
});
match(result, {
Ok: (value) => console.log("Success Value: " + value),
Err: (err) => console.log("Err Value: " + err),
});Usage with Option:
`const someValue: Option<number> = Some(10);
match(someValue, {
Some: (value) => console.log("Option has value: " + value),
None: () => console.log("Option is None"),
});
match(someValue, {
Some: (value) => Ok(value),
None: () => Err("Option is None"),
});API Reference
Result<T, E>
Methods
isOk(): this is Ok<T>- Checks if the result is an
Okinstance. - Returns:
trueif it's anOk,falseotherwise.
- Checks if the result is an
isErr(): this is Err<E>- Checks if the result is an
Errinstance. - Returns:
trueif it's anErr,falseotherwise.
- Checks if the result is an
unwrap(): T- Retrieves the value contained in an
Okinstance. - Throws an
Errorif called on anErrinstance.
- Retrieves the value contained in an
unwrapErr(): E- Retrieves the error contained in an
Errinstance. - Throws an
Errorif called on anOkinstance.
- Retrieves the error contained in an
map<U>(fn: (value: T) => U): Result<U, E>- Applies a function
fnto the value of anOkinstance and returns a newResultwith the transformed value. - If the
Resultis anErr, it returns the originalErrwithout applying the function. - Parameters:
fn: (value: T) => U: The function to apply to the value.
- Returns: A new
Resultwith the transformed value or the originalErr.
- Applies a function
flatMap<U>(fn: (value: T) => Result<U, E>): Result<U, E>- Applies a function
fnthat returns aResultto the value of anOkinstance. - If the
Resultis anErr, it returns the originalErr. - Parameters:
fn: (value: T) => Result<U, E>: The function to apply to the value.
- Returns: The result of applying the function or the original
Err.
- Applies a function
mapErr<U extends Error>(fn: (err: E) => U): Result<T, U>- Applies a function
fnto the error of anErrinstance and returns a newResultwith the transformed error. - If the
Resultis anOk, it returns the originalOkwithout applying the function. - Parameters:
fn: (err: E) => U: The function to apply to the error.
- Returns: A new
Resultwith the transformed error or the originalOk.
- Applies a function
Option<T>
Methods
isSome(): this is Some<T>- Checks if the option is a
Someinstance. - Returns:
trueif it's aSome,falseotherwise.
- Checks if the option is a
isNone(): this is None- Checks if the option is a
Noneinstance. - Returns:
trueif it's aNone,falseotherwise.
- Checks if the option is a
unwrap(): T- Retrieves the value contained in a
Someinstance. - Throws an
Errorif called on aNoneinstance.
- Retrieves the value contained in a
map<U>(fn: (value: T) => U): Option<U>- Applies a function
fnto the value of aSomeinstance and returns a newOptionwith the transformed value. - If the
OptionisNone, it returnsNone. - Parameters:
fn: (value: T) => U: The function to apply to the value.
- Returns: A new
Optionwith the transformed value orNone.
- Applies a function
flatMap<U>(fn: (value: T) => Option<U>): Option<U>- Applies a function
fnthat returns anOptionto the value of aSomeinstance. - If the
OptionisNone, it returnsNone. - Parameters:
fn: (value: T) => Option<U>: The function to apply to the value.
- Returns: The result of applying the function or
None.
- Applies a function
unwrapOr(defaultValue: T): T- Retrieves the value contained in a
Someinstance. - If the
OptionisNone, it returns the provideddefaultValue. - Parameters:
defaultValue: T: The value to return if theOptionisNone.
- Returns: The value of the
Someinstance or thedefaultValue.
- Retrieves the value contained in a
match Function
- Provides pattern matching for
ResultandOptiontypes. - Requires handlers for all possible cases (
Ok,ErrforResult;Some,NoneforOption).
Work in Progress (WIP)
Result
Current Implementation
The Result type currently implements the following methods:
-
isOk(): Checks if the result isOk. -
isErr(): Checks if the result isErr. -
unwrap(): Extracts the successful value or throws an error. -
unwrapErr(): Extracts the error value. -
map(fn): Maps a successful value using a function. -
flatMap(fn): Applies a function that returns aResult. -
mapErr(fn): Maps an error value using a function. -
ok(): ConvertsResult<T, E>intoOption<T>.
Methods to be Developed
The following methods are planned for future development:
-
ok(): ConvertsResult<T, E>intoOption<T>. -
err(): ConvertsResult<T, E>intoOption<E>. -
and(res): ReturnsErrifselfisErr, otherwise returnsres. -
andThen(fn): Callsfnif the result isOk, otherwise returnsErr. -
or(res): ReturnsOkifselfisOk, otherwise returnsres. -
orElse(fn): Callsfnif the result isErr, otherwise returnsOk. -
unwrapOr(defaultValue): Extracts the successful value or returns a default value. -
unwrapOrElse(fn): Extracts the successful value or calls a function to get a default value. -
transpose(): Transposes aResult<Option<T>, E>into anOption<Result<T, E>>. -
flatten(): Flattens a nestedResult<Result<T, E>, E>into aResult<T, E>.
Option
Current Implementation
The Option type currently implements the following methods:
-
isSome(): Checks if the option isSome. -
isNone(): Checks if the option isNone. -
unwrap(): Extracts the value or throws an error ifNone. -
map(fn): Maps aSomevalue using a function. -
flatMap(fn): Applies a function that returns anOption. -
unwrapOr(defaultValue): Extracts the value or returns a default value.
Methods to be Developed
The following methods are planned for future development:
-
expect(message): Extracts the value or throws an error with a custom message ifNone. -
okOr(err): ConvertsOption<T>intoResult<T, E>. -
okOrElse(errFn): ConvertsOption<T>intoResult<T, E>using a function to create the error. -
and(optb): ReturnsNoneifselfisNone, otherwise returnsoptb. -
andThen(fn): Callsfnif the option isSome, otherwise returnsNone. -
or(optb): ReturnsselfifSome, otherwise returnsoptb. -
orElse(fn): ReturnsselfifSome, otherwise callsfnto get anOption. -
unwrapOrElse(fn): Extracts the value or calls a function to get a default value. -
filter(predicate): ReturnsSomeif the value matches the predicate, otherwiseNone. -
zip(other): Zips twoOptionvalues into a tuple if both areSome. -
zipWith(other, fn): Zips twoOptionvalues using a function if both areSome. -
transpose(): Transposes anOption<Result<T, E>>into aResult<Option<T>, E>.
Contributing
Contributions to this package are welcome. Feel free to open issues and submit pull requests.