#How to handle nullish values
To make a nullable lookup type-safe, convert its result into an Option at the source, then compose from there. This guide collects the patterns for the nullish values you'll often meet in real code.
#Turn Array.find into an Option
find returns undefined when nothing matches. To work with the result type-safely, wrap the lookup with fn:
import { import Option Option } from "byenull";
type type User = {
id: string;
name: string;
}
User = { id: string id : string; name: string name : string };
const const users: User[] users : type User = {
id: string;
name: string;
}
User [] = [
{ id: string id : "u1", name: string name : "Alice" },
{ id: string id : "u2", name: string name : "Bob" },
];
const const findUser: (id: string, users: User[]) => Option.Option<User> findUser = import Option Option .function fn<(id: string, users: User[]) => User | undefined>(fn: (id: string, users: User[]) => User | undefined): (id: string, users: User[]) => Option.Option<User> (+1 overload)Wraps a function and returns a new function that returns an
Option
or
OptionAsync
.
Nullish values and Promise rejections produce
None
; synchronous throws are not captured.
@typeParamF - The function type to wrap.@returnsA new function that returns an Option or OptionAsync.@exampleSynchronous Function
import { Option } from 'byenull';
type User = { id: string; name: string };
const findUser = Option.fn((id: string, users: User[]) =>
users.find((user) => user.id === id),
);
findUser('u1', [{ id: 'u1', name: 'Alice' }]);
// { type: 'Some', value: { id: 'u1', name: 'Alice' } }
@exampleAsynchronous Function
import { Option } from 'byenull';
type User = { id: string; name: string };
const fetchUser = Option.fn(async (id: string) => {
const response = await fetch(`/api/users/${id}`);
return response.json() as Promise<User>;
});
await fetchUser('u1');
// { type: 'Some', value: { id: 'u1', name: 'Alice' } }
@seemaybe - For wrapping a thunk that takes no parameters.@categoryCreators fn ((id: string id : string, users: User[] users : type User = {
id: string;
name: string;
}
User []) => users: User[] users .Array<User>.find(predicate: (value: User, index: number, obj: User[]) => unknown, thisArg?: any): User | undefined (+1 overload)Returns the value of the first element in the array where predicate is true, and undefined
otherwise.
@parampredicate find calls predicate once for each element of the array, in ascending
order, until it finds one where predicate returns true. If such an element is found, find
immediately returns that element value. Otherwise, find returns undefined.@paramthisArg If provided, it will be used as the this value for each invocation of
predicate. If it is not provided, undefined is used instead. find ((user: User user ) => user: User user .id: string id === id: string id ));
const const alice: Option.Option<User> alice = const findUser: (id: string, users: User[]) => Option.Option<User> findUser ("u1", const users: User[] users );
// { type: 'Some', value: { id: 'u1', name: 'Alice' } }
const const nobody: Option.Option<User> nobody = const findUser: (id: string, users: User[]) => Option.Option<User> findUser ("u404", const users: User[] users );
// { type: 'None' }To keep chaining, see pipe basics.
#Read from a Map with some
Map.get returns V | undefined. Pass the result straight through some, which normalizes undefined into a None:
import { import Option Option } from "byenull";
const const settings: Map<string, string> settings = new var Map: MapConstructor
new <string, string>(iterable?: Iterable<readonly [string, string]> | null | undefined) => Map<string, string> (+3 overloads)
Map <string, string>([["theme", "dark"]]);
const const theme: string theme = import Option Option .function pipe<Option.Option<string>, string>(a: Option.Option<string>, ab: (a: Option.Option<string>) => string): string (+25 overloads)Applies a sequence of functions to a value, from left to right.
This utility enables function composition in a left-to-right manner.
It supports up to 25 chained functions from A through Z.
@typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@exampleimport { Option } from 'byenull';
const result = Option.pipe(
2,
x => x + 1,
x => x * 3,
x => `Result: ${x}`
);
// Result: 9
@categoryUtilities pipe (import Option Option .function some<string | undefined>(value: string | undefined): Option.Option<string>Creates a
Some
from a given value.
Passing null or undefined returns
None
instead.
@typeParamT - The type of the value to wrap.@returnsA Some containing the value, or None if the value is nullish.@exampleimport { Option } from 'byenull';
const some = Option.some(42);
// { type: 'Some', value: 42 }
const none = Option.some(null);
// { type: 'None' }
@categoryCreators some (const settings: Map<string, string> settings .Map<string, string>.get(key: string): string | undefinedReturns a specified element from the Map object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map.
@returnsReturns the element associated with the specified key. If no element is associated with the specified key, undefined is returned. get ("theme")), import Option Option .function unwrap<string>(defaultValue: string): <O>(option: O & ([string] extends [Option.InferSome<O> | null | undefined] ? unknown : never)) => Option.Unwrapped<O, string, Option.InferSome<O>>Extracts the value from an
Option
or
OptionAsync
.
If the input is a
None
, the default value is returned.
@typeParamD - The default value type.@exampleSome Case
import { Option } from 'byenull';
const value = Option.pipe(
Option.some(2),
Option.unwrap(0),
);
// 2
@exampleNone Case
import { Option } from 'byenull';
const empty: Option.Option<number> = Option.none();
const value = Option.pipe(
empty,
Option.unwrap(0),
);
// 0
@exampleNullish Default
import { Option } from 'byenull';
const value: number | null = Option.pipe(
Option.some(2),
Option.unwrap(null),
);
@seeorElse - For recovering with a fallback Option instead of a plain value.@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryUnwraps unwrap ("light"));
// 'dark', or 'light' when the key is missing#Query the DOM with maybe
DOM lookups return null when nothing matches. To evaluate a lookup immediately, use maybe:
import { import Option Option } from "byenull";
const const main: Option.Option<HTMLElement> main = import Option Option .function maybe<() => HTMLElement | null>(fn: () => HTMLElement | null): Option.Option<HTMLElement> (+1 overload)Executes a function and wraps its result in an
Option
or
OptionAsync
.
Nullish values and Promise rejections produce
None
; synchronous throws are not captured.
@typeParamF - The function type to execute.@returnsAn Option or OptionAsync wrapping the function's return value.@exampleSynchronous Thunk
import { Option } from 'byenull';
const option = Option.maybe(() => document.querySelector('#app'));
// { type: 'Some', value: HTMLElement } or { type: 'None' }
@exampleAsynchronous Thunk
import { Option } from 'byenull';
type Config = { host: string };
const option = await Option.maybe(() =>
fetch('/api/config').then((response) => response.json() as Promise<Config>),
);
// { type: 'Some', value: Config }
@seefn - For wrapping functions that take parameters.@categoryCreators maybe (() => var document: Documentwindow.document returns a reference to the document contained in the window.
document .ParentNode.querySelector<"main">(selectors: "main"): HTMLElement | null (+4 overloads)Returns the first element that is a descendant of node that matches selectors.
querySelector ("main"));
// Some<HTMLElement> or None#Read environment variables safely
process.env values are string | undefined. To handle a missing variable without a null check, wrap the read:
import { import Option Option } from "byenull";
const const apiUrl: string apiUrl = import Option Option .function pipe<Option.Option<string>, string>(a: Option.Option<string>, ab: (a: Option.Option<string>) => string): string (+25 overloads)Applies a sequence of functions to a value, from left to right.
This utility enables function composition in a left-to-right manner.
It supports up to 25 chained functions from A through Z.
@typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@exampleimport { Option } from 'byenull';
const result = Option.pipe(
2,
x => x + 1,
x => x * 3,
x => `Result: ${x}`
);
// Result: 9
@categoryUtilities pipe (
import Option Option .function some<string | undefined>(value: string | undefined): Option.Option<string>Creates a
Some
from a given value.
Passing null or undefined returns
None
instead.
@typeParamT - The type of the value to wrap.@returnsA Some containing the value, or None if the value is nullish.@exampleimport { Option } from 'byenull';
const some = Option.some(42);
// { type: 'Some', value: 42 }
const none = Option.some(null);
// { type: 'None' }
@categoryCreators some (var process: NodeJS.Process process .NodeJS.Process.env: NodeJS.ProcessEnvThe process.env property returns an object containing the user environment.
See environ(7).
An example of this object looks like:
{
TERM: 'xterm-256color',
SHELL: '/usr/local/bin/bash',
USER: 'maciej',
PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
PWD: '/Users/maciej',
EDITOR: 'vim',
SHLVL: '1',
HOME: '/Users/maciej',
LOGNAME: 'maciej',
_: '/usr/local/bin/node'
}
It is possible to modify this object, but such modifications will not be
reflected outside the Node.js process, or (unless explicitly requested)
to other Worker threads.
In other words, the following example would not work:
node -e 'process.env.foo = "bar"' && echo $foo
While the following will:
import { env } from 'node:process';
env.foo = 'bar';
console.log(env.foo);
Assigning a property on process.env will implicitly convert the value
to a string. This behavior is deprecated. Future versions of Node.js may
throw an error when the value is not a string, number, or boolean.
import { env } from 'node:process';
env.test = null;
console.log(env.test);
// => 'null'
env.test = undefined;
console.log(env.test);
// => 'undefined'
Use delete to delete a property from process.env.
import { env } from 'node:process';
env.TEST = 1;
delete env.TEST;
console.log(env.TEST);
// => undefined
On Windows operating systems, environment variables are case-insensitive.
import { env } from 'node:process';
env.TEST = 1;
console.log(env.test);
// => 1
Unless explicitly specified when creating a Worker instance,
each Worker thread has its own copy of process.env, based on its
parent thread's process.env, or whatever was specified as the env option
to the Worker constructor. Changes to process.env will not be visible
across Worker threads, and only the main thread can make changes that
are visible to the operating system or to native add-ons. On Windows, a copy of process.env on a Worker instance operates in a case-sensitive manner
unlike the main thread.
@sincev0 .1.27 env .string | undefined API_URL ),
import Option Option .function unwrap<string>(defaultValue: string): <O>(option: O & ([string] extends [Option.InferSome<O> | null | undefined] ? unknown : never)) => Option.Unwrapped<O, string, Option.InferSome<O>>Extracts the value from an
Option
or
OptionAsync
.
If the input is a
None
, the default value is returned.
@typeParamD - The default value type.@exampleSome Case
import { Option } from 'byenull';
const value = Option.pipe(
Option.some(2),
Option.unwrap(0),
);
// 2
@exampleNone Case
import { Option } from 'byenull';
const empty: Option.Option<number> = Option.none();
const value = Option.pipe(
empty,
Option.unwrap(0),
);
// 0
@exampleNullish Default
import { Option } from 'byenull';
const value: number | null = Option.pipe(
Option.some(2),
Option.unwrap(null),
);
@seeorElse - For recovering with a fallback Option instead of a plain value.@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryUnwraps unwrap ("http://localhost:3000"),
);#Absorb nullish values from a third-party SDK
If a library returns null for "not found" instead of throwing, wrap the call with fn and the nullish result becomes a None:
declare function function getFeatureFlag(key: string): boolean | null getFeatureFlag (key: string key : string): boolean | null;
import { import Option Option } from "byenull";
const const isEnabled: Option.Option<NonNullable<boolean | null>> isEnabled = import Option Option .function fn<(key: string) => boolean | null>(fn: (key: string) => boolean | null): (key: string) => Option.Option<NonNullable<boolean | null>> (+1 overload)Wraps a function and returns a new function that returns an
Option
or
OptionAsync
.
Nullish values and Promise rejections produce
None
; synchronous throws are not captured.
@typeParamF - The function type to wrap.@returnsA new function that returns an Option or OptionAsync.@exampleSynchronous Function
import { Option } from 'byenull';
type User = { id: string; name: string };
const findUser = Option.fn((id: string, users: User[]) =>
users.find((user) => user.id === id),
);
findUser('u1', [{ id: 'u1', name: 'Alice' }]);
// { type: 'Some', value: { id: 'u1', name: 'Alice' } }
@exampleAsynchronous Function
import { Option } from 'byenull';
type User = { id: string; name: string };
const fetchUser = Option.fn(async (id: string) => {
const response = await fetch(`/api/users/${id}`);
return response.json() as Promise<User>;
});
await fetchUser('u1');
// { type: 'Some', value: { id: 'u1', name: 'Alice' } }
@seemaybe - For wrapping a thunk that takes no parameters.@categoryCreators fn (function getFeatureFlag(key: string): boolean | null getFeatureFlag )("beta-ui");
// Some<boolean> or None#Fetch data that may be missing
To handle an API that resolves with null or rejects, wrap the request with fn. The asynchronous path converts both a nullish resolution and a rejection into a None:
import { import Option Option } from "byenull";
type type User = {
id: string;
name: string;
}
User = { id: string id : string; name: string name : string };
const const fetchUser: (id: string) => Option.OptionAsync<User> fetchUser = import Option Option .function fn<(id: string) => Promise<User | null>>(fn: (id: string) => Promise<User | null>): (id: string) => Option.OptionAsync<User> (+1 overload)Wraps a function and returns a new function that returns an
Option
or
OptionAsync
.
Nullish values and Promise rejections produce
None
; synchronous throws are not captured.
@typeParamF - The function type to wrap.@returnsA new function that returns an Option or OptionAsync.@exampleSynchronous Function
import { Option } from 'byenull';
type User = { id: string; name: string };
const findUser = Option.fn((id: string, users: User[]) =>
users.find((user) => user.id === id),
);
findUser('u1', [{ id: 'u1', name: 'Alice' }]);
// { type: 'Some', value: { id: 'u1', name: 'Alice' } }
@exampleAsynchronous Function
import { Option } from 'byenull';
type User = { id: string; name: string };
const fetchUser = Option.fn(async (id: string) => {
const response = await fetch(`/api/users/${id}`);
return response.json() as Promise<User>;
});
await fetchUser('u1');
// { type: 'Some', value: { id: 'u1', name: 'Alice' } }
@seemaybe - For wrapping a thunk that takes no parameters.@categoryCreators fn (async (id: string id : string) => {
const const response: Response response = await function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> fetch (`/api/users/${id: string id }`);
return const response: Response response .Body.json(): Promise<any> json () as interface Promise<T>Represents the completion of an asynchronous operation
Promise <type User = {
id: string;
name: string;
}
User | null>;
});
const const user: Option.Option<User> user = await const fetchUser: (id: string) => Option.OptionAsync<User> fetchUser ("u1");
// Some<User>, or None when the request fails or the API returns null#When the source throws instead of returning nullish
fn and maybe convert nullish return values and rejected promises. A synchronous throw propagates to the caller. To absorb a throwing API such as JSON.parse, convert the throw into a nullish value yourself:
import { import Option Option } from "byenull";
const const parseJson: (text: string) => Option.Option<{}> parseJson = import Option Option .function fn<(text: string) => unknown>(fn: (text: string) => unknown): (text: string) => Option.Option<{}> (+1 overload)Wraps a function and returns a new function that returns an
Option
or
OptionAsync
.
Nullish values and Promise rejections produce
None
; synchronous throws are not captured.
@typeParamF - The function type to wrap.@returnsA new function that returns an Option or OptionAsync.@exampleSynchronous Function
import { Option } from 'byenull';
type User = { id: string; name: string };
const findUser = Option.fn((id: string, users: User[]) =>
users.find((user) => user.id === id),
);
findUser('u1', [{ id: 'u1', name: 'Alice' }]);
// { type: 'Some', value: { id: 'u1', name: 'Alice' } }
@exampleAsynchronous Function
import { Option } from 'byenull';
type User = { id: string; name: string };
const fetchUser = Option.fn(async (id: string) => {
const response = await fetch(`/api/users/${id}`);
return response.json() as Promise<User>;
});
await fetchUser('u1');
// { type: 'Some', value: { id: 'u1', name: 'Alice' } }
@seemaybe - For wrapping a thunk that takes no parameters.@categoryCreators fn ((text: string text : string): unknown => {
try {
return var JSON: JSONAn intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.
JSON .JSON.parse(text: string, reviver?: (this: any, key: string, value: any) => any): anyConverts a JavaScript Object Notation (JSON) string into an object.
@paramtext A valid JSON string.@paramreviver A function that transforms the results. This function is called for each member of the object.
If a member contains nested objects, the nested objects are transformed before the parent object is.@throws{SyntaxError} If text is not valid JSON. parse (text: string text );
} catch {
return var undefined undefined ;
}
});
const const json: Option.Option<{}> json = const parseJson: (text: string) => Option.Option<{}> parseJson ('{"name": "Alice"}');
// { type: 'Some', value: { name: 'Alice' } }
const const broken: Option.Option<{}> broken = const parseJson: (text: string) => Option.Option<{}> parseJson ("not json");
// { type: 'None' }If the operation can meaningfully fail with an error worth keeping, model it as a Result with @praha/byethrow instead. See converting between Option and Result for how.