crab-salad
v3.0.1
Published
A lightweight TypeScript library for Result<T, E> and Option<T>, inspired by Rust.
Maintainers
Readme
Crab Salad
A lightweight TypeScript library for
Result<T, E>andOption<T>, inspired by Rust.
Disclaimer
This project provides a beautiful and expressive way to handle errors and optional values using functional-style constructs like Result and Option. It aims to improve code readability and robustness in a way inspired by languages like Rust.
However, this approach does not follow the idiomatic or native error-handling patterns of JavaScript/TypeScript, such as exceptions and nullable types.
Therefore, while it's a useful learning tool or for internal experimentation, I do not recommend using this in production environments.
Use it to explore better patterns — but weigh it against the expectations and conventions of the JS/TS ecosystem.
Installation
npm install crab-saladResult<T, E>
Represents either a successful value (Ok) or an error (Err).
import { Ok } from 'crab-salad';
const result = Ok(5).map((x) => x * 2); // Ok(10)
if (result.isOk) {
console.log(result.unwrap());
}API
result.and(other)result.andThen(fn)result.err()result.expect(msg)result.expectErr(msg)result.flatten()result.inspectOk(fn)result.inspectErr(fn)result.isErrresult.isErrAnd(fn)result.isOkresult.isOkAnd(fn)result.map(fn)result.mapErr(fn)result.mapOr(other, fn)result.mapOrElse(otherFn, fn)result.ok()result.or(other)result.orElse(fn)result.transpose()result.unwrap()result.unwrapErr()result.unwrapOr(other)result.unwrapOrElse(fn)
Result.fromPromise(promise, mapErr)Result.fromAsyncFn(fn, mapErr)result.match({ ok, err })result.toPromise()Result.tryCatch(fn, mapErr)result.unzip()result.zip(other)result.zipWith(other, fn)
Option<T>
Represents an optional value: Some(value) or None.
import { Option } from 'crab-salad';
const maybeName = Option.fromNullable('Alice');
maybeName.match({
some: (val) => console.log('Name:', val),
none: () => console.log('No name found'),
});API
option.and(other)option.andThen(fn)option.expect(msg)option.filter(fn)option.flatten()option.inspectSome(fn)option.isNoneoption.isNoneOr(fn)option.isSomeoption.isSomeAnd(fn)option.map(fn)option.mapOr(other, fn)option.mapOrElse(fn, fn)option.okOr(err)option.okOrElse(fn)option.or(other)option.orElse(fn)option.transpose()option.unwrap()option.unwrapOr(other)option.unwrapOrElse(fn)option.unzip()option.xor(other)option.zip(other)option.zipWith(other, fn)
Docs
See Docs for full working examples of each method.
Running Tests
npm run testUses Vitest for fast TypeScript unit testing.
Changelog
See CHANGELOG.md for a list of changes.
License
MIT
