An opinionated functional programming library for TypeScript.
A collection of utilities and mechanisms brought over from languages like Rust and Erlang. Each utility is deliberately selected and built from scratch with zero dependencies.
npm i slang-tsWell I love functional programming so much and hate classes and inheritance with all my heart, sorry no offense intended, I prefer composition and functions over those but well that's not exactly why I made this despite part of the reasons, main reason was all functional programming (FP) libraries in typescript and javascript were really complicated, think effect ts and rameda, all seemed like needed one to be so nerdy, so was like I need something simple I can work with comfortably and can onboard a team to over an evenning, one by one, got each utility crafted out, to what you see today, here I aimed more for practicality than correctness, so yes some functions are not pure, a few rules broken, a few opinions, and all that makes this fun to use, try it!
So let's say your function can fail. Instead of throwing, you return a Result: Ok with the
value or Err with a message, and the caller checks isOk before reading either:
import { Ok, Err, type Result, println } from "slang-ts";
function splitBill(total: number, people: number): Result<number, string> {
if (people === 0) {
return Err("Add at least one person to split the bill");
}
return Ok(total / people);
}
const share = splitBill(120, 4);
if (share.isOk) {
println("Each person pays:", share.value); // 30
} else {
println("Could not split the bill:", share.error);
}println is optional: it's a small development logger, silent in production.
Import only what you use:
import { option, Ok, Err, atom, match } from "slang-ts";| If you need… | Use |
|---|---|
| A value which may be missing | Option |
| An operation which can fail | Result and SafeTry |
| Several results checked together | combineResults and combineErrors |
| Pattern matching over results | Match |
| Steps which stop at the first failure | Pipe |
| Timeout, retry, or cancellation | SuperPromise |
| Ordered, parallel, or race tasks | SuperRunner |
| A shared concurrency limit | taskGroup |
| Strict array bounds or paging | list |
| Nested record reads with defaults | struct |
| Set membership and set operations | sets |
Lazy pipelines over an Ok |
Ok.iterate |
| Cached function calls | memoized |
| Step history or undo | createStepper |
| Events between parts of an app | Channel |
| A lifecycle trigger which fires once | Signal |
- Result (
Ok,Err, expect, unwrap with else, andThen, mapErr, orFn, raw cause) - SafeTry (
safeTry) - combineResults and combineErrors (
combineResults,combineErrors) - Option (
option, Some, None,isFalsy, expect, unwrap with else, andThen) - Match (
match,matchAll) - Options (
Options) - Pipe (
pipe) - Panic (
panic)
- list (
list) - struct (
struct) - sets (
sets) - Ok.iterate (
Ok(value).iterate()) - memoized (
memoized)
- SuperPromise (
superPromise) - SuperRunner (
superRunner: sequence, all, race) - taskGroup (
taskGroup) - Signal (
createSignal) - Channel (
createChannel: send, subscribe, when) - createStepper (
createStepper)
- println (
println,setEnvironment)
Full reference: docs index. Feature list: CHANGELOG.md. Agent guide: skill/SKILL.md.
Loading saved settings can fail two ways: the saved text is not valid JSON, or the role inside
is one you do not support. safeTry turns both into one Result:
import { Ok, Err, safeTry, type Result, println } from "slang-ts";
type Role = "admin" | "member";
type SavedSettings = {
role: string;
};
function parseRole(value: string): Result<Role, string> {
if (value === "admin" || value === "member") {
return Ok(value);
}
return Err("Unknown role");
}
const savedText = '{"role":"admin"}';
const role = safeTry(() => {
const settings = JSON.parse(savedText) as SavedSettings;
return parseRole(settings.role);
});
if (role.isOk) {
println("Role:", role.value); // "admin"
} else {
println("Could not load the role:", role.error);
}A throw from JSON.parse and an Err from parseRole both come back as Err, so you check
the result once. safeTry itself never throws. Your function is sync here, so the Result
comes back directly; an async function gives you a promise of it to await.
Full detail: SafeTry and Result.
Your function receives an AbortSignal to pass along to fetch. timeout stops an attempt
once it takes too long, retry runs it again after a failure, and the call resolves to Ok or
Err. It never rejects:
import { superPromise, println } from "slang-ts";
type User = {
id: string;
name: string;
};
const user = await superPromise(
async (signal: AbortSignal): Promise<User> => {
const response = await fetch("https://example.com/api/users/u_1", { signal });
if (!response.ok) {
throw new Error("Could not load the user");
}
return (await response.json()) as User;
},
{ timeout: 5000, retry: 2 }, // 5 seconds per attempt, up to 2 retries
);
if (user.isOk) {
println("User:", user.value.name); // "Ada"
} else {
println("Could not load the user:", user.error);
}Full detail: SuperPromise.
list keeps bounds strict: a range outside the array fails instead of returning fewer items. struct
reads and shapes records, keeping only the fields you choose.
import { list, struct, println } from "slang-ts";
type User = {
id: string;
name: string;
avatar?: string;
email: string;
};
const users: User[] = [
{ id: "u_1", name: "Ada", avatar: "/avatars/ada.png", email: "ada@example.com" },
{ id: "u_2", name: "Grace", email: "grace@example.com" },
{ id: "u_3", name: "Linus", email: "linus@example.com" },
];
const page = 1;
const size = 2;
const total = list(users).count().else(0);
const start = Math.min(page * size, total);
const end = Math.min(start + size, total);
const paged = list(users).range(start, end).else([]);
const cards = paged.map((user) => struct(user).pick("id", "name", "avatar").else(user));
println(cards); // [{"id":"u_3","name":"Linus"}]list never shortens a range, so the example clamps the window and lets the last page
be short. struct then keeps only the fields the card needs.
Install with Bun, then run the full check:
bun install
bun run exportexport runs the tests, checks types, and builds minified ESM with bundled declarations into
dist/. npm publish runs it through prepublishOnly, so you never ship stale output. Tests live
in tests.
Building needs Node.js ^22.18.0 || ^24.11.0 || >=26.0.0. That's for the build tool, not for
projects using Slang.
Got a utility from another language which belongs here? Open an issue or a pull request. Contributions are welcome.
- ESM only. You'll use
import;requireisn't supported. - Node.js 20+ or a modern browser.
- TypeScript 5.9.x or 7.0.x if you want the bundled types. Plain JavaScript works too.
- Zero runtime dependencies.
MIT License. See LICENSE.