TypeScript goodies inspired by Rust.
This project draws inspiration from Rust, but is designed to be more ergonomic and tailored to TypeScript's features and syntax.
npm add @wopjs/tsur
import { Option, Some, None } from "@wopjs/tsur";
const maybeNumber = Some(42);
if (maybeNumber.isSome()) {
console.log(maybeNumber.unwrap()); // 42
} else {
console.log("There is no number");
}
const maybeString = None;
if (maybeString.isSome()) {
console.log(maybeString.unwrap());
} else {
console.log("There is no string"); // "There is no string"
}
import { Result, Ok, Err } from "@wopjs/tsur";
function divide(a: number, b: number): Result<number, string> {
if (b === 0) {
return Err("Cannot divide by zero");
}
return Ok(a / b);
}
const result = divide(10, 2);
if (result.isOk()) {
console.log(result.unwrap()); // 5
} else {
console.log(result.unwrapErr()); // "Cannot divide by zero"
}
import { Option } from "@wopjs/tsur";
function get(obj: any, key: string): Option<any> {
return key in obj ? Some(obj[key]) : None;
}
const obj = {
a: {
b: {
c: 42,
},
},
};
const result = get(obj, "a")
.map(x => x.b)
.unwrapOr("default");
Many useful array methods are added:
import { filterMap, Some, None } from "@wopjs/tsur";
const arr = [1, 2, 3, 4, 5];
const result = filterMap(arr, x => (x % 2 === 0 ? Some(x * 2) : None));
console.log(result); // [4, 8]
Or you can patch them to the native array:
import "@wopjs/tsur/patches/array";
const arr = [1, 2, 3, 4, 5];
const result = arr.filterMap(x => (x % 2 === 0 ? Some(x * 2) : None));
console.log(result); // [4, 8]
See docs for more details.
MIT @ CRIMX