@dbidwell94/ts-utils v0.4.1
TypeScript Rust-Like Utility Types
A TypeScript library that provides utility types inspired by Rust's powerful type system, including Result<T, E>
and Option<T>
. These types help to enhance type safety and improve error handling in TypeScript applications.
Installation
You can install the library via npm:
npm install @dbidwell94/ts-utils
Usage
Option
The Option<T>
type is used to represent a value that can either be Some(value)
or None
. This is useful for scenarios where a value may or may not be present.
import { Option, some, none } from '@dbidwell94/ts-utils';
// Example usage
function findUserById(id: string): Option<User> {
const user = database.find(user => user.id === id);
return user ? some(user) : none();
}
const userOption = findUserById('123');
if (userOption.isSome()) {
console.log(`Found user: ${userOption.value}`);
} else {
console.log('User not found');
}
Result<T, E>
The Result<T, E>
type is used to represent the result of an operation that can either succeed with a value of type T
or fail with an error of type E
. This is ideal for handling operations that can fail.
import { Result, ok, err } from '@dbidwell94/ts-utils';
// Example usage
function divide(a: number, b: number): Result<number> { // Result<T> can be used instead of `Result<T, Error>`, however you can make the 2nd type param anything that extends `Error`
if (b === 0) {
return err(new Error('Cannot divide by zero'));
}
return ok(a / b);
}
const result = divide(10, 0);
if (result.isOk()) {
console.log(`Result: ${result.value}`);
} else {
console.error(`Error: ${result.error}`);
}
API Reference
Option<T>
some(value: T)
: Represents a value that is present.none()
: Represents the absence of a value.isSome()
: Returnstrue
if the option contains a value.isNone()
: Returnstrue
if the option does not contain a value.unwrap()
: Returns the value contained inSome
, or throws an error if it isNone
.unwrapOr(err: E)
: Returns the value contained inSome
, or throws the provided error if it isNone
.map(newValue: NewT)
: Maps the value ofT
into aNewT
if the provided value isSome
.serialize()
: Converts theOption
into a serializable Option without any helper functions. Useful if you want to store theOption
in Redux, or send the value over the netfromSerializableOption(option: SerializableOption)
: Converts aSerializableOption
into anOption
with all the helper functions
Result<T, E>
ok(value: T)
: Represents a successful result.err(error: E)
: Represents a failed result.isOk()
: Returnstrue
if the result is successful.isError()
: Returnstrue
if the result is an error.unwrap()
: Returns the value contained inOk
, or throws an error if it isErr
.unwrapOr(default: T)
: Returns the value contained inOk
, or returns the default valueT
.unwrapOrElse(error: E)
: Returns the value contained inOk
, or throws the provided errorE
.ok()
: Converts theResult<T, E>
into anOption<T>
.err()
: Converts theResult<T, E>
into anOption<E>
.mapOk(newValue: NewT)
: Maps the value ofT
into aNewT
, returning a newResult<NewT, E>
.mapErr(newError: NewE)
: Maps the errorE
into aNewE
, returning a newResult<T, NewE>
.
Contributing
Contributions are welcome! Please open an issue or submit a pull request if you'd like to add features or fix bugs.
- Fork the repository.
- Create a new branch (
git checkout -b feature-branch
). - Make your changes.
- Commit your changes (
git commit -m 'Add some feature'
). - Push to the branch (
git push origin feature-branch
). - Create a new Pull Request.
License
This project is licensed under the MIT License. See the LICENSE file for details.
Acknowledgements
Inspired by the elegant type system of Rust, this library aims to bring similar concepts to TypeScript for improved type safety and error handling.