#Creating Options
Now that we know what an Option looks like, let's create them with the library's helper functions and point our user lookup at the directory from the last chapter.
#Creating a Some with some
some creates a Some that holds the given value:
import { import Option Option } from "byenull";
const const option: Option.Option<number> option = import Option Option .function some<number>(value: number): Option.Option<number>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 (42);
// { type: 'Some', value: 42 }some also normalizes: passing null or undefined returns a None, so a Some always holds a real value:
import { import Option Option } from "byenull";
import Option Option .function some<null>(value: null): Option.Option<never>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 (null);
// { type: 'None' }
import Option Option .function some<undefined>(value: undefined): Option.Option<never>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 undefined undefined );
// { type: 'None' }This makes some handy at the edge of our code, where nullable values arrive from the outside:
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"]]);
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"));
// { type: 'Some', value: 'dark' }
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 ("language"));
// { type: 'None' }#Creating a None with none
none creates the Option that holds nothing:
import { import Option Option } from "byenull";
const const option: Option.Option<never> option = import Option Option .function none(): Option.Option<never>Creates a
None
: an Option that holds no value.
@returnsA None.@exampleimport { Option } from 'byenull';
const option = Option.none();
// { type: 'None' }
@categoryCreators none ();
// { type: 'None' }#Returning Options from functions
The most common way to use some and none is to return them from our own functions, in place of null or undefined:
import { import Option Option } from "byenull";
type type User = {
id: string;
name: string;
}
User = { id: string id : string; name: string name : string };
const const findUser: (id: string, users: User[]) => Option.Option<User> findUser = (id: string id : string, users: User[] users : type User = {
id: string;
name: string;
}
User []): import Option Option .type Option<T> = Option.Some<T> | Option.NoneA union type representing either a
Some
or a
None
.
@typeParamT - The type of the Some value.@exampleimport { Option } from 'byenull';
const doSomething = (): Option.Option<number> => {
return Math.random() > 0.5
? Option.some(10)
: Option.none();
};
@categoryCore Types Option <type User = {
id: string;
name: string;
}
User > => {
const const user: User | undefined 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 );
if (const user: User | undefined user === var undefined undefined ) {
return import Option Option .function none(): Option.Option<never>Creates a
None
: an Option that holds no value.
@returnsA None.@exampleimport { Option } from 'byenull';
const option = Option.none();
// { type: 'None' }
@categoryCreators none ();
}
return import Option Option .function some<User>(value: User): Option.Option<User>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 user: User user );
};
const findUser: (id: string, users: User[]) => Option.Option<User> findUser ("u1", [{ id: string id : "u1", name: string name : "Alice" }]);
// { type: 'Some', value: { id: 'u1', name: 'Alice' } }
const findUser: (id: string, users: User[]) => Option.Option<User> findUser ("u404", [{ id: string id : "u1", name: string name : "Alice" }]);
// { type: 'None' }#Wrapping lookups with fn
Writing the if by hand gets repetitive. fn wraps a function that may return a nullish value, so the wrapping happens once:
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 findProfile: (userId: string, profiles: Profile[]) => Option.Option<Profile> findProfile = import Option Option .function fn<(userId: string, profiles: Profile[]) => Profile | undefined>(fn: (userId: string, profiles: Profile[]) => Profile | undefined): (userId: string, profiles: Profile[]) => Option.Option<Profile> (+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 ((userId: string userId : string, profiles: Profile[] profiles : type Profile = {
userId: string;
displayName?: string;
}
Profile []) =>
profiles: Profile[] profiles .Array<Profile>.find(predicate: (value: Profile, index: number, obj: Profile[]) => unknown, thisArg?: any): Profile | 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 ((profile: Profile profile ) => profile: Profile profile .userId: string userId === userId: string userId ),
);
const findUser: (id: string, users: User[]) => Option.Option<User> findUser ("u1", const users: User[] users );
// { type: 'Some', value: { id: 'u1', name: 'Alice' } }
const findProfile: (userId: string, profiles: Profile[]) => Option.Option<Profile> findProfile ("u2", const profiles: Profile[] profiles );
// Bob has no profile: { type: 'None' }The wrapped function keeps its parameters, and its nullish results become None.
fn converts nullish return values. If the wrapped function throws synchronously, the throw still propagates. See Design Principles for why.
#Running a lookup immediately with maybe
maybe runs a thunk, a function with no parameters, and wraps its result:
import { import Option Option } from "byenull";
const const theme: Option.Option<Element> theme = import Option Option .function maybe<() => Element | null>(fn: () => Element | null): Option.Option<Element> (+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<Element>(selectors: string): Element | null (+4 overloads)Returns the first element that is a descendant of node that matches selectors.
querySelector ('meta[name="theme-color"]'));
// Some<HTMLMetaElement> or NoneUse maybe when there is nothing to pass, and fn when there is.
#Async wrappers
Both fn and maybe handle asynchronous functions: the result becomes an OptionAsync, and a rejected promise becomes a None:
import { import Option Option } from "byenull";
type type Avatar = {
url: string;
}
Avatar = { url: string url : string };
const const fetchAvatar: (userId: string) => Option.OptionAsync<Avatar> fetchAvatar = import Option Option .function fn<(userId: string) => Promise<Avatar | null>>(fn: (userId: string) => Promise<Avatar | null>): (userId: string) => Option.OptionAsync<Avatar> (+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 (userId: string userId : string) => {
const const response: Response response = await function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> fetch (`/api/avatars/${userId: string userId }`);
return const response: Response response .Body.json(): Promise<any> json () as interface Promise<T>Represents the completion of an asynchronous operation
Promise <type Avatar = {
url: string;
}
Avatar | null>;
});
const const avatar: Option.Option<Avatar> avatar = await const fetchAvatar: (userId: string) => Option.OptionAsync<Avatar> fetchAvatar ("u1");
// Some<Avatar>, or None when the request failed or returned nullWe will use this fetch in the chaining chapter.