A TypeScript library providing Rust-inspired Option
and Result
types for robust error handling and explicit value presence.
Option<T>
Type: Represents the presence (Some
) or absence (None
) of a value, helping to eliminatenull
andundefined
related bugs.Result<T, E>
Type: Encapsulates either a successful value (Ok
) or an error (Err
), promoting explicit error handling over exceptions.- Functional API: Provides
map
,flatMap
,orElse
,filter
, andmatch
functions for composing operations onOption
andResult
types. fromThrowable
: A utility to convert potentially throwing functions intoOption
orResult
returning functions, enabling a more functional error handling style.- Clean API: Designed for ease of use and integration into existing TypeScript projects.
npm install @mikkurogue/option-ts
# or
yarn add @mikkurogue/option-ts
import { Option, Some, None, ifSome, unwrapOption, unwrapOrOption } from '@mikkurogue/option-ts';
function getUserById(id: string): Option<{ name: string }> {
if (id === "123") {
return Some({ name: "Alice" });
}
return None();
}
const user = getUserById("123");
ifSome(user, (u) => {
console.log(`User found: ${u.name}`);
});
const userName = unwrapOrOption(user, { name: "Guest" }).name;
console.log(userName); // Alice
const nonExistentUser = getUserById("456");
const defaultUserName = unwrapOrOption(nonExistentUser, { name: "Guest" }).name;
console.log(defaultUserName); // Guest
import { Result, Ok, Err, match, fromThrowable } from '@mikkurogue/option-ts';
function divide(a: number, b: number): Result<number, string> {
if (b === 0) {
return Err("Cannot divide by zero");
}
return Ok(a / b);
}
const division1 = divide(10, 2);
match(
division1,
(val) => console.log(`Result: ${val}`), // Result: 5
(err) => console.error(`Error: ${err}`)
);
const division2 = divide(10, 0);
match(
division2,
(val) => console.log(`Result: ${val}`),
(err) => console.error(`Error: ${err}`) // Error: Cannot divide by zero
);
const safeParseJson = fromThrowable(
JSON.parse,
(e) => (e as Error).message
);
const parsedJson = safeParseJson('{"key": "value"}');
match(
parsedJson,
(data) => console.log("Parsed JSON:", data), // Parsed JSON: { key: 'value' }
(error) => console.error("JSON Error:", error)
);
For more detailed information and examples, please refer to the full documentation.
This project uses tsgo as its build system for fast and efficient compilation.
Contributions are welcome, in any form you'd like.