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.
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 thetypes
array:"types": ["vitest/globals", "@consolidados/results/globals"]
-
Import in Entry Point (e.g.,
main.ts
orindex.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
, andmatch
directly in your code without explicit imports.
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
}
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");
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");
-
isOk(): this is Ok<T>
: Checks if the result is a successfulOk
value. -
isErr(): this is Err<E>
: Checks if the result is a failedErr
value. -
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 aResult
to 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
.
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);
Represents an Option
that does not contain a value.
Example:
const absentValue: Option<string> = None();
-
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 aSome
or 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 anOption
to the value of aSome
. -
unwrapOr(defaultValue: T): T
: Extracts the value from aSome
or returns a default value if it'sNone
.
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"),
});
-
isOk(): this is Ok<T>
- Checks if the result is an
Ok
instance. - Returns:
true
if it's anOk
,false
otherwise.
- Checks if the result is an
-
isErr(): this is Err<E>
- Checks if the result is an
Err
instance. - Returns:
true
if it's anErr
,false
otherwise.
- Checks if the result is an
-
unwrap(): T
- Retrieves the value contained in an
Ok
instance. - Throws an
Error
if called on anErr
instance.
- Retrieves the value contained in an
-
unwrapErr(): E
- Retrieves the error contained in an
Err
instance. - Throws an
Error
if called on anOk
instance.
- Retrieves the error contained in an
-
map<U>(fn: (value: T) => U): Result<U, E>
- Applies a function
fn
to the value of anOk
instance and returns a newResult
with the transformed value. - If the
Result
is anErr
, it returns the originalErr
without applying the function. - Parameters:
-
fn: (value: T) => U
: The function to apply to the value.
-
- Returns: A new
Result
with the transformed value or the originalErr
.
- Applies a function
-
flatMap<U>(fn: (value: T) => Result<U, E>): Result<U, E>
- Applies a function
fn
that returns aResult
to the value of anOk
instance. - If the
Result
is 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
fn
to the error of anErr
instance and returns a newResult
with the transformed error. - If the
Result
is anOk
, it returns the originalOk
without applying the function. - Parameters:
-
fn: (err: E) => U
: The function to apply to the error.
-
- Returns: A new
Result
with the transformed error or the originalOk
.
- Applies a function
-
isSome(): this is Some<T>
- Checks if the option is a
Some
instance. - Returns:
true
if it's aSome
,false
otherwise.
- Checks if the option is a
-
isNone(): this is None
- Checks if the option is a
None
instance. - Returns:
true
if it's aNone
,false
otherwise.
- Checks if the option is a
-
unwrap(): T
- Retrieves the value contained in a
Some
instance. - Throws an
Error
if called on aNone
instance.
- Retrieves the value contained in a
-
map<U>(fn: (value: T) => U): Option<U>
- Applies a function
fn
to the value of aSome
instance and returns a newOption
with the transformed value. - If the
Option
isNone
, it returnsNone
. - Parameters:
-
fn: (value: T) => U
: The function to apply to the value.
-
- Returns: A new
Option
with the transformed value orNone
.
- Applies a function
-
flatMap<U>(fn: (value: T) => Option<U>): Option<U>
- Applies a function
fn
that returns anOption
to the value of aSome
instance. - If the
Option
isNone
, 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
Some
instance. - If the
Option
isNone
, it returns the provideddefaultValue
. - Parameters:
-
defaultValue: T
: The value to return if theOption
isNone
.
-
- Returns: The value of the
Some
instance or thedefaultValue
.
- Retrieves the value contained in a
- Provides pattern matching for
Result
andOption
types. - Requires handlers for all possible cases (
Ok
,Err
forResult
;Some
,None
forOption
).
The Result
type currently implements the following methods:
- [x]
isOk()
: Checks if the result isOk
. - [x]
isErr()
: Checks if the result isErr
. - [x]
unwrap()
: Extracts the successful value or throws an error. - [x]
unwrapErr()
: Extracts the error value. - [x]
map(fn)
: Maps a successful value using a function. - [x]
flatMap(fn)
: Applies a function that returns aResult
. - [x]
mapErr(fn)
: Maps an error value using a function. - [x]
ok()
: ConvertsResult<T, E>
intoOption<T>
.
The following methods are planned for future development:
- [ ]
ok()
: ConvertsResult<T, E>
intoOption<T>
. - [ ]
err()
: ConvertsResult<T, E>
intoOption<E>
. - [ ]
and(res)
: ReturnsErr
ifself
isErr
, otherwise returnsres
. - [ ]
andThen(fn)
: Callsfn
if the result isOk
, otherwise returnsErr
. - [ ]
or(res)
: ReturnsOk
ifself
isOk
, otherwise returnsres
. - [ ]
orElse(fn)
: Callsfn
if 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>
.
The Option
type currently implements the following methods:
- [x]
isSome()
: Checks if the option isSome
. - [x]
isNone()
: Checks if the option isNone
. - [x]
unwrap()
: Extracts the value or throws an error ifNone
. - [x]
map(fn)
: Maps aSome
value using a function. - [x]
flatMap(fn)
: Applies a function that returns anOption
. - [x]
unwrapOr(defaultValue)
: Extracts the value or returns a default value.
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)
: ReturnsNone
ifself
isNone
, otherwise returnsoptb
. - [ ]
andThen(fn)
: Callsfn
if the option isSome
, otherwise returnsNone
. - [ ]
or(optb)
: Returnsself
ifSome
, otherwise returnsoptb
. - [ ]
orElse(fn)
: Returnsself
ifSome
, otherwise callsfn
to get anOption
. - [ ]
unwrapOrElse(fn)
: Extracts the value or calls a function to get a default value. - [ ]
filter(predicate)
: ReturnsSome
if the value matches the predicate, otherwiseNone
. - [ ]
zip(other)
: Zips twoOption
values into a tuple if both areSome
. - [ ]
zipWith(other, fn)
: Zips twoOption
values using a function if both areSome
. - [ ]
transpose()
: Transposes anOption<Result<T, E>>
into aResult<Option<T>, E>
.
Contributions to this package are welcome. Feel free to open issues and submit pull requests.