rustlike-ts v1.0.1
rustlike-ts
This library provides Rust-like Result and Option types for TypeScript, allowing for expressive and safe error handling.
Features
- Rust-inspired syntax: Enjoy Rust-like constructs and style in your TypeScript code.
- Improved safety: Leverage concepts from Rust to write more robust, error-free code.
- Performance-focused: Designed with performance in mind, offering an efficient and streamlined development process.
Installation
npm install rustlike-tsResult<T, E>
The Result<T, E> type represents either success (Ok(T)) or failure (Err(E)).
Methods
unwrap(): Returns the contained value ifOk, otherwise throws an error.unwrapOr(or: T): Returns the contained value ifOk, otherwise returns the provided default value.unwrapOrElse(fn: (error: E) => T): Computes a default value using the provided function.expect(message: string): Returns the contained value or throws an error with a custom message.expectErr(message: string): Returns the contained error or throws an error ifOk.isOk(): ReturnstrueifOk.isErr(): ReturnstrueifErr.ok(): ConvertsResult<T, E>toOption<T>(Some(T)ifOk, otherwiseNone).err(): ConvertsResult<T, E>toOption<E>(Some(E)ifErr, otherwiseNone).map(fn: (data: T) => T): Applies a function to theOkvalue.mapErr(fn: (err: E) => E): Applies a function to theErrvalue.and<U>(result: Result<U, E>): ReturnsErrifErr, otherwise returns the providedResult<U, E>.andThen<U>(fn: (data: T) => Result<U, E>): Applies a function to theOkvalue.or(result: Result<T, E>): ReturnsOkifOk, otherwise returns the provided alternative.orElse<F>(fn: (err: E) => Result<T, F>): Applies a function to theErrvalue.
Usage
import { Ok, Err, type Result } from "rustlike-ts";
function divide(a: number, b: number): Result<number, string> {
if (b === 0) return Err("Division by zero");
return Ok(a / b);
}
const result = divide(10, 2);
console.log(result.unwrap()); // 5Option
The Option<T> type represents a value that may or may not be present (Some(T) or None).
Methods
isSome(): ReturnstrueifSome.isNone(): ReturnstrueifNone.unwrap(): Returns the contained value ifSome, otherwise throws an error.expect(message: string): Returns the contained value or throws an error with a custom message.unwrapOr(or: T): Returns the contained value ifSome, otherwise returns the default.unwrapOrElse(fn: () => T): Computes a value using the provided function.map(fn: (data: T) => T): Applies a function to the contained value.mapOr(fallback: T, fn: (data: T) => T): Returns the mapped value or fallback.mapOrElse(noneFn: () => T, someFn: (data: T) => T): Applies different functions forSomeorNone.and(option: Option<T>): ReturnsNoneifNone, otherwise returns the providedOption<T>.or(or: Option<T>): ReturnsSomeifSome, otherwise returns the alternative.andThen(fn: (data: T) => Option<T>): Applies a function ifSome.filter(fn: (data: T) => boolean): ReturnsSomeif the predicate is true, otherwiseNone.
Usage
import { Some, None, type Option } from "rustlike-ts";
function findUser(id: number): Option<string> {
const users = { 1: "Alice", 2: "Bob" };
return users[id] ? Some(users[id]) : None;
}
const user = findUser(1);
console.log(user.unwrap()); // AliceError Handling
ResultError
A custom error class used for Result errors.
class ResultError extends Error {
readonly name = "ResultError";
}OptionError
A custom error class used for Option errors.
class OptionError extends Error {
readonly name = "OptionError";
}Utility Functions for Matching Result and Option
This module provides utility functions for handling Result and Option types in a structured manner. The functions allow executing specific logic based on the state of these types, improving code clarity and reducing the need for explicit conditional checks.
matchResult<T, E, R>
Description
Matches a Result<T, E> and executes the corresponding function based on its state:
- If the
ResultisOk, it callsop.Okwith the contained value. - If the
ResultisErr, it callsop.Errwith the contained error.
This function provides a structured way to handle success and error cases, reducing the need for manual conditionals.
Parameters
result: Result<T, E>- TheResultinstance to match.op: { Ok: (data: T) => R; Err: (error: E) => R }- An object containing callback functions:Ok(data: T): R- Function executed ifresultisOk, receiving the contained value.Err(error: E): R- Function executed ifresultisErr, receiving the contained error.
Returns
R - The return value of the executed function.
Example
const result: Result<number, string> = getResult();
const message = matchResult(result, {
Ok: (value) => `Success: ${value}`,
Err: (error) => `Error: ${error}`,
});
console.log(message);matchOption<T, R>
Description
Matches an Option<T> and executes the corresponding function based on its state:
- If the
OptionisSome, it callsop.Somewith the contained value. - If the
OptionisNone, it callsop.None.
This function allows handling optional values in a structured way, eliminating explicit if statements.
Parameters
result: Option<T>- TheOptioninstance to match.op: { Some: (data: T) => R; None: () => R }- An object containing callback functions:Some(data: T): R- Function executed ifresultisSome, receiving the contained value.None(): R- Function executed ifresultisNone.
Returns
R - The return value of the executed function.
Example
const option: Option<string> = getOption();
const result = matchOption(option, {
Some: (value) => `Value: ${value}`,
None: () => "No value found",
});
console.log(result);