tsentials/maybe
Maybe<T> makes optionality explicit. No null reference errors — the absence of a value is a first-class concept.
Installation
npm install tsentials
Import
import { Maybe, MaybeAsync, tryFirst, tryLast, tryFind, choose, asMaybe } from 'tsentials/maybe';
Type Definition
type Maybe<T> =
| { readonly hasValue: true; readonly value: T }
| { readonly hasValue: false };
The discriminant is hasValue: boolean — there is no kind property.
Creating Maybe
// From a nullable value — null/undefined → None, value → Some
const name: Maybe<string> = Maybe.from(user.nickname);
// Explicit constructors
const some: Maybe<string> = Maybe.some('Alice');
const none: Maybe<string> = Maybe.none();
// A Some never holds null/undefined: some(null) is None, and a null/undefined
// result from map/mapIf/mapAsync/bind/bindIf/bindAsync also becomes None
Maybe.isNone(Maybe.some(null)); // true
// From a factory function — thrown errors become None, null/undefined become None
const parsed: Maybe<Config> = Maybe.fromTry(() => JSON.parse(raw));
Type Guards
if (Maybe.isSome(maybe)) {
console.log(maybe.value); // T — narrowed by type guard
}
if (Maybe.isNone(maybe)) {
console.log('No value');
}
Checking Value
// Pattern match — preferred over hasValue checks
const display = Maybe.match(
maybe,
name => `Hello, ${name}`, // some
() => 'Hello, stranger', // none
);
// Void-only pattern match — side effects without returning a value
Maybe.switch(maybe,
user => console.log(`Found ${user.name}`),
() => console.log('User not found'),
);
Transforming
// map: transform the inner value if present
const upper: Maybe<string> = Maybe.map(
Maybe.from(user.email),
e => e.toLowerCase(),
);
// filter: discard value if predicate fails
const nonEmpty: Maybe<string> = Maybe.filter(upper, s => s.length > 0);
// bind: flatMap — when the transform itself returns Maybe<T>
const address: Maybe<Address> = Maybe.bind(
Maybe.from(user),
u => Maybe.from(u.address),
);
// flatten: unwrap nested Maybe<Maybe<T>> → Maybe<T>
const flat: Maybe<string> = Maybe.flatten(nestedMaybe);
// toArray: Some → [value], None → []
const arr: string[] = Maybe.toArray(maybe);
Side Effects
// tap: run side effect when Some, returns the same Maybe
Maybe.tap(maybe, value => console.log('Got:', value));
// tapNone: run side effect when None, returns the same Maybe
Maybe.tapNone(maybe, () => console.log('Value was missing'));
Conditional Pipeline
// mapIf: transform only if condition is true, otherwise pass through
// Condition can be a boolean or a predicate (value) => boolean
const formatted = Maybe.mapIf(maybe, s => s.length > 0, s => s.trim());
const toggled = Maybe.mapIf(maybe, shouldFormat, s => s.toUpperCase());
// bindIf: flatMap only if condition is true, otherwise pass through
const enriched = Maybe.bindIf(maybe, shouldEnrich, id => lookupById(id));
Consuming / Extraction
// getOrDefault — provide a default value directly
const email = Maybe.getOrDefault(Maybe.from(user.email), 'no-email@fallback.com');
// getOrElse — provide a fallback factory (lazy, only invoked when None)
const email2 = Maybe.getOrElse(Maybe.from(user.email), () => 'no-email@fallback.com');
// getOrUndefined — native TypeScript idiom: T | undefined
const email3: string | undefined = Maybe.getOrUndefined(Maybe.from(user.email));
// getOrThrow — throws Error if None
const email4 = Maybe.getOrThrow(Maybe.from(user.email), 'Email is required');
// getOrThrowFactory — throws custom error if None
const email5 = Maybe.getOrThrowFactory(maybe, () => new DomainError('User.NoEmail'));
// match — handle both cases and return a value
const label = Maybe.match(maybe, v => `Found: ${v}`, () => 'Not found');
// deconstruct — [hasValue, value | undefined] tuple
const [hasVal, val] = Maybe.deconstruct(maybe);
// tryGet — same as deconstruct, atomic extraction
const [ok, value] = Maybe.tryGet(maybe);
// format — 'Some(value)' / 'None'; nested Maybes are formatted recursively
Maybe.format(Maybe.some(1)); // 'Some(1)'
Maybe.format(Maybe.some(Maybe.none())); // 'Some(None)'
// (named format, not toString: an own toString would break String(Maybe))
Fallback Chain
// or: return the Maybe if Some, otherwise return the fallback Maybe
const result = Maybe.or(primary, fallbackMaybe);
// orElse: lazy fallback — factory only invoked when None
const result2 = Maybe.orElse(primary, () => computeFallback());
Async Pipeline
// mapAsync: transform with an async function
const fetched: Maybe<User> = await Maybe.mapAsync(
Maybe.some(userId),
async id => fetchUser(id),
);
// bindAsync: flatMap with an async function that returns Maybe<T>
const detail: Maybe<Profile> = await Maybe.bindAsync(
Maybe.some(userId),
async id => {
const user = await fetchUser(id);
return Maybe.from(user?.profile);
},
);
// filterAsync: async predicate — becomes None if predicate returns false
const valid: Maybe<User> = await Maybe.filterAsync(
Maybe.some(user),
async u => await checkIsActive(u.id),
);
// tapAsync: async side effect without altering the Maybe
await Maybe.tapAsync(maybe, async value => await logAccess(value));
// tapNoneAsync: async side effect when None
await Maybe.tapNoneAsync(maybe, async () => await logMiss());
// matchAsync: async pattern match
const result = await Maybe.matchAsync(
maybe,
async user => await enrichUser(user),
async () => await getDefaultUser(),
);
// orAsync: async fallback — factory only invoked when None
const result2 = await Maybe.orAsync(maybe, async () => await fetchFallback());
Fluent Async Chain (MaybeAsync)
MaybeAsync<T> wraps a Promise<Maybe<T>>, like ResultAsync does for Result. Every step
returns a MaybeAsync synchronously and you await once at the end (await gives a Maybe<T>).
Callbacks can be sync or async.
import { MaybeAsync } from 'tsentials/maybe';
const name: string = await MaybeAsync.from(repo.find(id)) // Promise<Maybe<T>>, Maybe<T> or MaybeAsync<T>
.filter(user => user.isActive)
.bind(async user => Maybe.from(await loadProfile(user.id)))
.map(profile => profile.displayName) // null/undefined result → None
.tap(async n => audit(n))
.tapNone(() => log('missing'))
.orElse(() => Maybe.some('guest'))
.getOrElse(() => 'anonymous');
// Factories: MaybeAsync.from / some / none / try (same rules as Maybe.fromTryAsync)
// Terminals: match(onSome, onNone), getOrElse(fn), getOrDefault(value), or just await
// Bridge: toResult(error?) → ResultAsync<T> (default error as Maybe.toResult)
const user = await MaybeAsync.from(repo.find(id)).toResult(Err.notFound('User.NotFound', 'No user'));
Every step (map, bind, filter, tap, tapNone, orElse, match, getOrElse) takes an
optional last argument { signal }:
- the callback receives the signal as its last parameter;
- if the signal is already aborted when the callback would run, the step rejects with
signal.reason and the callback is not called;
- if the signal aborts while the callback is pending, the step rejects at once (the callback's
work is not stopped; pass the signal into it for that);
- a step whose callback does not run (for example
mapon None) ignores the signal.
await MaybeAsync.some(id).bind((id, signal) => repo.find(id, { signal }), { signal });
Collection Utilities
import { tryFirst, tryLast, tryFind, choose, asMaybe } from 'tsentials/maybe';
// tryFirst — first element (optionally the first matching one) or None
const first: Maybe<User> = tryFirst(users);
const firstAdmin: Maybe<User> = tryFirst(users, u => u.role === 'admin');
// tryLast — last element (optionally the last matching one) or None
const last: Maybe<User> = tryLast(users);
// tryFind — first matching element, Map entry or own record key, or None
const admin: Maybe<User> = tryFind(users, u => u.role === 'admin');
const cached: Maybe<User> = tryFind(userMap, 42); // ReadonlyMap<number, User>
const port: Maybe<number> = tryFind(config, 'port'); // own key of a plain object
// A found element that is null/undefined gives None
// choose — filter out Nones, unwrap Somes; or map each item through a selector
const values: number[] = choose([Maybe.some(1), Maybe.none(), Maybe.some(3)]);
// => [1, 3]
const ids: number[] = choose(users, u => Maybe.from(u.externalId));
// asMaybe — shorthand for Maybe.from()
const m: Maybe<string> = asMaybe(nullableValue);
Full Example
const users = [
{ name: 'Alice', role: 'admin', email: 'alice@example.com' },
{ name: 'Bob', role: 'user', email: null },
];
// Find first admin
const adminName = Maybe.match(
tryFind(users, u => u.role === 'admin'),
u => u.name,
() => 'No admin',
);
// Collect all non-null emails
const emails = choose(users.map(u => Maybe.from(u.email)));
// Safe parsing with fromTry
const config = Maybe.fromTry(() => JSON.parse(rawInput));
// Fallback chain
const display = Maybe.getOrElse(
Maybe.or(Maybe.from(user.nickname), Maybe.from(user.email)),
() => 'anonymous',
);
Complete API Reference
| Category | Method | Signature |
|----------|--------|-----------|
| Factory | some | <T>(value: T) => Maybe<T> |
| | none | <T>() => Maybe<T> |
| | from | <T>(value: T \| null \| undefined) => Maybe<T> |
| | fromTry | <T>(fn: () => T \| null \| undefined) => Maybe<T> |
| Type Guard | isSome | <T>(m: Maybe<T>) => m is { hasValue: true; value: T } |
| | isNone | <T>(m: Maybe<T>) => m is { hasValue: false } |
| Transform | map | <T, U>(m, fn) => Maybe<U> |
| | bind | <T, U>(m, fn: (v: T) => Maybe<U>) => Maybe<U> |
| | filter | <T>(m, pred) => Maybe<T> |
| | flatten | <T>(m: Maybe<Maybe<T>>) => Maybe<T> |
| | toArray | <T>(m) => T[] |
| Side Effect | tap | <T>(m, fn: (v: T) => void) => Maybe<T> |
| | tapNone | <T>(m, fn: () => void) => Maybe<T> |
| Conditional | mapIf | <T>(m, cond: boolean \| ((v: T) => boolean), fn) => Maybe<T> |
| | bindIf | <T>(m, cond: boolean \| ((v: T) => boolean), fn) => Maybe<T> |
| Match | match | <T, U>(m, onSome, onNone) => U |
| | switch | <T>(m, onSome, onNone) => void |
| Extraction | getOrDefault | <T>(m, default: T) => T |
| | getOrElse | <T>(m, fn: () => T) => T |
| | getOrUndefined | <T>(m) => T \| undefined |
| | getOrThrow | <T>(m, message?) => T |
| | getOrThrowFactory | <T>(m, factory: () => Error) => T |
| | deconstruct | <T>(m) => [boolean, T \| undefined] |
| | tryGet | <T>(m) => [boolean, T \| undefined] |
| Formatting | format | <T>(m) => string — Some(value) / None |
| Fallback | or | <T>(m, fallback: Maybe<T>) => Maybe<T> |
| | orElse | <T>(m, fn: () => Maybe<T>) => Maybe<T> |
| Async | mapAsync | <T, U>(m, fn) => Promise<Maybe<U>> |
| | bindAsync | <T, U>(m, fn) => Promise<Maybe<U>> |
| | filterAsync | <T>(m, pred) => Promise<Maybe<T>> |
| | tapAsync | <T>(m, fn) => Promise<Maybe<T>> |
| | tapNoneAsync | <T>(m, fn: () => Promise<void>) => Promise<Maybe<T>> |
| | matchAsync | <T, U>(m, onSome, onNone) => Promise<U> |
| | orAsync | <T>(m, fn) => Promise<Maybe<T>> |
| MaybeAsync | from / some / none / try | static factories → MaybeAsync<T> |
| | map / bind / filter / tap / tapNone / orElse | (fn, { signal }?) => MaybeAsync |
| | toResult | (error?) => ResultAsync<T> |
| | match / getOrElse / getOrDefault | terminal, => Promise<...> |
| Collection | tryFirst | <T>(items: Iterable<T>, pred?) => Maybe<T> |
| | tryLast | <T>(items: Iterable<T>, pred?) => Maybe<T>; a non-array iterable is read to the end |
| | tryFind | <T>(arr, pred) => Maybe<T>; also (map, key) and (record, key) |
| | choose | <T>(maybes: Iterable<Maybe<T>>) => T[]; also (items: Iterable<T>, selector) => U[] |
| | asMaybe | <T>(value: T \| null \| undefined) => Maybe<T> |
Best Practices
- Use
Maybe.from()for all nullable-to-Maybe conversions - Prefer
Maybe.match()overhasValuechecks to avoid branching - Use
Maybe.isSome()/Maybe.isNone()type guards when you need narrowing in if-blocks - Use
Maybe.bind()when the transform can itself be absent (returnsMaybe<T>) - Use
Maybe.fromTry()to safely wrap expressions that may throw - Use
choose()to extract present values from aMaybe<T>[]array - The discriminant is
hasValue: boolean— there is nokindproperty