@onrails/maybe API
Complete API reference for @onrails/maybe
@onrails/maybe API Reference
Constructors
none ƒ
The None value — represents expected absence. Not a failure.
function none<T = never>(): Maybe<T>Example
const cached: Maybe<User> = cache.has(id) ? some(cache.get(id)) : none();some ƒ
Lifts a value into the Some branch.
function some<T>(value: T): Maybe<T>Parameters
| Parameter | Type | Description |
|---|---|---|
value | T |
Example
const m = some(1); // Maybe<number>Core
andThen ƒ
Neverthrow-compat alias of flatMap — same dual-form shape. Prefer
flatMap as the canonical name; reach for andThen only when porting
neverthrow code or matching its vocabulary.
function andThen<T, U>(maybe: Maybe<T>, fn: (value: T) => Maybe<U>): Maybe<U>
function andThen<T, U>(fn: (value: T) => Maybe<U>): (maybe: Maybe<T>) => Maybe<U>Parameters
| Parameter | Type | Description |
|---|---|---|
maybe | Maybe<T> | |
fn | (value: T) => Maybe<U> |
Example
andThen(fromNullable(user), (u) =>
u.active ? some(u) : none(),
);at ƒ
Element at index, or None when out of range. A negative index counts
from the end, as Array.prototype.at. An element that is undefined is
still Some(undefined).
function at<T>(items: readonly T[], index: number): Maybe<T>
function at(index: number): <T>(items: readonly T[]) => Maybe<T>Parameters
| Parameter | Type | Description |
|---|---|---|
items | readonly T[] | |
index | number |
Example
at(["a", "b"], -1); // Some("b")
at(["a", "b"], 5); // None
pipe(rows, at(0)); // curriedfind ƒ
First element that matches pred, or None. Stops at the first match. A
type-guard predicate narrows the result.
function find<T, S extends T>(items: Iterable<T>, pred: (item: T) => item is S): Maybe<S>
function find<T>(items: Iterable<T>, pred: (item: T) => boolean): Maybe<T>
function find<T, S extends T>(pred: (item: T) => item is S): (items: Iterable<T>) => Maybe<S>
function find<T>(pred: (item: T) => boolean): (items: Iterable<T>) => Maybe<T>Parameters
| Parameter | Type | Description |
|---|---|---|
items | Iterable<T> | |
pred | (item: T) => item is S |
Example
find(users, (u) => u.id === id); // Maybe<User>
find(events, (e): e is Click => e.type === "click"); // Maybe<Click>flatMap ƒ
Canonical bind for Maybe. Chains a Maybe-returning step;
short-circuits on None. Dual-form.
function flatMap<T, U>(maybe: Maybe<T>, fn: (value: T) => Maybe<U>): Maybe<U>
function flatMap<T, U>(fn: (value: T) => Maybe<U>): (maybe: Maybe<T>) => Maybe<U>Parameters
| Parameter | Type | Description |
|---|---|---|
maybe | Maybe<T> | |
fn | (value: T) => Maybe<U> |
Example
flatMap(fromNullable(user), (u) =>
u.active ? some(u) : none(),
);head ƒ
First element of an iterable, or None when it is empty. Pulls one element
only.
function head<T>(items: Iterable<T>): Maybe<T>Parameters
| Parameter | Type | Description |
|---|---|---|
items | Iterable<T> |
Example
head([3, 4]); // Some(3)
head(new Set()); // NoneisNone ƒ
Type-narrowing predicate: returns true when the value is None.
function isNone<T>(maybe: Maybe<T>): maybe is { readonly _tag: "None"; } & MaybeMethods<never>Parameters
| Parameter | Type | Description |
|---|---|---|
maybe | Maybe<T> |
Example
if (isNone(fromNullable(user))) {
return redirect("/login"); // narrowed to None branch
}isSome ƒ
Type-narrowing predicate: returns true when the value is Some.
function isSome<T>(maybe: Maybe<T>): maybe is { readonly _tag: "Some"; readonly value: T; } & MaybeMethods<T>Parameters
| Parameter | Type | Description |
|---|---|---|
maybe | Maybe<T> |
Example
if (isSome(m)) {
console.log(m.value); // narrowed to Some branch
}last ƒ
Last element of an iterable, or None when it is empty. Reads arrays by
index; walks any other iterable to the end.
function last<T>(items: Iterable<T>): Maybe<T>Parameters
| Parameter | Type | Description |
|---|---|---|
items | Iterable<T> |
Example
last([3, 4]); // Some(4)
last([]); // Nonemap ƒ
Transform the Some value, passing None through unchanged. Dual-form.
function map<T, U>(maybe: Maybe<T>, fn: (value: T) => U): Maybe<U>
function map<T, U>(fn: (value: T) => U): (maybe: Maybe<T>) => Maybe<U>Parameters
| Parameter | Type | Description |
|---|---|---|
maybe | Maybe<T> | |
fn | (value: T) => U |
Example
map(some(2), (n) => n * 3); // Some 6 — data-first
pipe(fromNullable(input), map((s) => s.trim())); // curriedmatch ƒ
Terminal collapse — fold both branches into a single value. Positional,
dual-form. Same shape as Result.match for sibling consistency.
For files that also import match from ts-pattern, use a namespace
import (import * as Maybe from "@onrails/maybe" → Maybe.match) to
dissolve the collision.
function match<T, U>(maybe: Maybe<T>, onSome: (value: T) => U, onNone: () => U): U
function match<T, U>(onSome: (value: T) => U, onNone: () => U): (maybe: Maybe<T>) => UParameters
| Parameter | Type | Description |
|---|---|---|
maybe | Maybe<T> | |
onSome | (value: T) => U | |
onNone | () => U |
Example
const greeting = match(
fromNullable(user),
(u) => `hello ${u.name}`,
() => "hello guest",
);MaybeData type
Plain-data shape of a Maybe: what JSON.parse, structuredClone
and postMessage hand back. It has no methods; lift it with Maybe.from.
export type MaybeData<T> = { readonly _tag: "Some"; readonly value: T } | { readonly _tag: "None" };MaybeMethods type
Methods every live Maybe carries on its (non-enumerable) prototype.
Core semantics, mirroring ResultMethods: tap does not swallow throws.
export interface MaybeMethods<T> {
/** Transform the `Some` value; `None` passes through. */
map<U>(fn: (value: T) => U): Maybe<U>;
/** Canonical bind; short-circuits on `None`. */
flatMap<U>(fn: (value: T) => Maybe<U>): Maybe<U>;
/** Alias of {@link MaybeMethods.flatMap}. */
andThen<U>(fn: (value: T) => Maybe<U>): Maybe<U>;
/** Fold both branches into one value. */
match<U>(onSome: (value: T) => U, onNone: () => U): U;
/** The `Some` value, or `defaultValue` on `None`. */
unwrapOr<U>(defaultValue: U): T | U;
/** Observe the `Some` value, pass the maybe through. */
tap(fn: (value: T) => void): Maybe<T>;
/** Observe `None`, pass the maybe through. */
tapNone(fn: () => void): Maybe<T>;
}of ƒ
Fantasy Land pure — alias of some. One lift name shared across
the trio (of / Result.of / ResultAsync.of) for generic and FL-style
code.
function of<T>(value: T): Maybe<T>Parameters
| Parameter | Type | Description |
|---|---|---|
value | T |
Example
const m = of(1); // Maybe<number> — identical to some(1)show ƒ
Debug printer — renders a maybe as Some(…) / None for logs. Payloads
print as JSON (values are plain data by design); non-JSON payloads fall
back to String(...). Mirror of the result package's show.
function show<T>(maybe: Maybe<T>): stringParameters
| Parameter | Type | Description |
|---|---|---|
maybe | Maybe<T> |
Example
show(some(1)); // 'Some(1)'
show(none()); // 'None'tap ƒ
Run a side effect on the Some value, pass the Maybe through unchanged.
None is a no-op. Mirrors tap from @onrails/result. Dual-form.
function tap<T>(maybe: Maybe<T>, fn: (value: T) => void): Maybe<T>
function tap<T>(fn: (value: T) => void): (maybe: Maybe<T>) => Maybe<T>Parameters
| Parameter | Type | Description |
|---|---|---|
maybe | Maybe<T> | |
fn | (value: T) => void |
Example
tap(some(2), (n) => console.log(n)); // logs 2, returns Some 2
pipe(fromNullable(row), tap((r) => sink.push(r))); // curried — collect on SometapNone ƒ
Run a side effect when the Maybe is None, pass it through unchanged.
Some is a no-op. The None-side mirror of tap. Dual-form.
function tapNone<T>(maybe: Maybe<T>, fn: () => void): Maybe<T>
function tapNone<T>(fn: () => void): (maybe: Maybe<T>) => Maybe<T>Parameters
| Parameter | Type | Description |
|---|---|---|
maybe | Maybe<T> | |
fn | () => void |
Example
tapNone(none(), () => metrics.miss()); // runs effect, returns None
pipe(fromNullable(hit), tapNone(() => metrics.miss())); // curriedunwrap ƒ
Unwraps the Some value or throws if the value is None.
function unwrap<T>(maybe: Maybe<T>): TParameters
| Parameter | Type | Description |
|---|---|---|
maybe | Maybe<T> |
Example
expect(unwrap(parseUser(raw))).toEqual(expected);unwrapOr ƒ
function unwrapOr<T, U>(maybe: Maybe<T>, defaultValue: U): T | U
function unwrapOr<U>(defaultValue: U): <T>(maybe: Maybe<T>) => U | TParameters
| Parameter | Type | Description |
|---|---|---|
maybe | Maybe<T> | |
defaultValue | U |
Collections
compact ƒ
Drop every None and collect the remaining Some values into an array.
function compact<T>(maybes: Iterable<Maybe<T>>): T[]Parameters
| Parameter | Type | Description |
|---|---|---|
maybes | Iterable<Maybe<T>> |
Example
compact([some(1), none(), some(2)]); // [1, 2]compactMap ƒ
Map each item to Maybe, drop None, collect the rest. One pass over any
iterable.
function compactMap<T, U>(items: Iterable<T>, fn: (item: T) => Maybe<U>): U[]Parameters
| Parameter | Type | Description |
|---|---|---|
items | Iterable<T> | |
fn | (item: T) => Maybe<U> |
Example
compactMap(rawRows, (row) =>
row.deletedAt ? none() : some(row.id),
);
// string[]Utilities
fromNullable ƒ
Lift a nullable value into Maybe<T> — null and undefined become
None; anything else becomes Some.
function fromNullable<T>(value: T | null | undefined): Maybe<T>Parameters
| Parameter | Type | Description |
|---|---|---|
value | T | null | undefined |
Example
fromNullable(cache.get(key)); // Maybe<V>
fromNullable(null); // Noneoptional ƒ
flatMap(fromNullable(value), fn) — lift a nullable then bind through
a Maybe-returning step. Convenient for chaining lookups.
function optional<T, U>(value: T | null | undefined, fn: (value: T) => Maybe<U>): Maybe<U>Parameters
| Parameter | Type | Description |
|---|---|---|
value | T | null | undefined | |
fn | (value: T) => Maybe<U> |
Example
optional(rawId, (id) => fromNullable(cache.get(id)));Types
Maybe type
Tagged optional value — a discriminated union over _tag where absence
(None) is an expected outcome, not a failure. Construct with some /
none, narrow with isSome / isNone, and collapse with
match.
Value-side companion of the Maybe type. from lifts plain data back
into a live Maybe at every deserialization sink (JSON.parse,
structuredClone, postMessage, Redux rehydration). It trusts the shape,
but an unknown _tag is a defect and throws a TypeError rather than
silently becoming None.
export type Maybe<T> = MaybeData<T> & MaybeMethods<T>;
const Maybe: { readonly from: <T>(data: MaybeData<T>) => Maybe<T>; }Example
function findUser(id: string): Maybe<User> {
return fromNullable(db.users.get(id));
}const live = Maybe.from<number>(JSON.parse(JSON.stringify(some(1))));
live.map((n) => n + 1);None type
The None branch of a Maybe — expected absence, tagged "None".
export type None = Extract<Maybe<never>, { _tag: "None" }>;Some type
The Some branch of a Maybe — a present value tagged "Some".
export type Some<T> = Extract<Maybe<T>, { _tag: "Some" }>;