A rusty Option for TypeScript.
Warning
This is a Proof of Concept (PoC). It’s not meant for production: each method is intentionally verbose to show how this PoC works. Use it to experiment and maybe get inspired to build something even better!
Here’s what makes rusty-option worth exploring:
-
if-let in TypeScript
Rust’s
if-let
is adapted to TypeScript usingfor-of
. This approach enables concise and readable handling of optional values. -
Minimal Core
The core implementation of
Some
andNone
is simple yet functional. Check out the code:
import { Option, Some, None } from "rusty-option";
let debug = Option.from(process.env.DEBUG);
for (let v of debug) {
console.log(`debug on: ${v}`);
}
let text = process.env.TEXT;
let result = Option.from(text.match(/rusty_(.+)/));
for (let [_, somethingRusty] of result) {
console.log(`rusty: ${somethingRusty}`);
}
let n = Math.random() > 0.5 ? Some("foo") : None;
n.map((n) => n.length).mapOr(42, (v) => v * 14); // 42;
See also:
- https://github.com/shqld/rusty-option/blob/main/example.test.ts
- https://github.com/shqld/rusty-option/blob/main/src/option.ts
$ npm i rusty-option