#Option type
In this tutorial we will build a small profile lookup: given a user ID, we will find a user, read their optional profile, and produce a display name, handling every "maybe it's not there" along the way. Before we write any function, let's look at what an Option actually is.
#What is an Option?
An Option represents the outcome of a lookup that may come up empty.
It is always one of two variants:
Somemeans the lookup produced a value.Nonemeans it produced nothing.
In some languages and libraries this is also called a Maybe type.
#The structure
An Option is a plain object with a type property that tells the two variants apart:
import { import Option Option } from "byenull";
// A Some holds a value
const const some: Option.Some<number> some : import Option Option .type Some<T> = {
readonly type: "Some";
readonly value: T;
}
The variant of an
Option
that holds a value.
@typeParamT - The type of the held value.@categoryCore Types Some <number> = {
type: "Some" type : "Some",
value: number value : 42,
};
// A None holds nothing
const const none: Option.None none : import Option Option .type None = {
readonly type: "None";
}
The variant of an
Option
that holds no value.
@categoryCore Types None = {
type: "None" type : "None",
};Because it is just an object, an Option can be logged, serialized to JSON, send freely between server and client or compared in tests as it is.
In practice, we rarely write these objects by hand. The next chapter shows the functions that create them.
#The union type
Option.Option<T> is the union of Some<T> and None.
T is the type of the value:
import { import Option Option } from "byenull";
// Returns either a Some<number> or a None
const const divide: (a: number, b: number) => Option.Option<number> divide = (a: number a : number, b: number b : number): 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 <number> => {
if (b: number b === 0) {
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<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 (a: number a / b: number b );
};A None never carries a value, so there is only one None type, and it is not generic.
#Why use an Option instead of nullish checks?
#1. One way to define missing value
In TypeScript we have multiple ways of defining a value that might be absent.
type type User = {
name: string | null;
avatar?: string | null;
age: number | undefined;
}
User = { name: string | null name : string | null, avatar?: string | null | undefined avatar ?: string | null, age: number | undefined age : number | undefined }With Option we can make this uniform:
type type User = {
name: Option.Option<string>;
avatar: Option.Option<string>;
age: Option.Option<number>;
}
User = {
name: Option.Option<string> name : 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 <string>,
avatar: Option.Option<string> avatar : 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 <string>,
age: Option.Option<number> age : 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 <number>
}#2. Option composes
Options can be chained, collecting possible some types in a union automatically and skipping steps when a value is None. We'll learn more about piping and transforming in Chaining Options.
const const result: number result = import Option Option .function pipe<Option.Option<number>, Option.Option<number>, Option.Option<number>, Option.Option<number>, number>(a: Option.Option<number>, ab: (a: Option.Option<number>) => Option.Option<number>, bc: (b: Option.Option<number>) => Option.Option<number>, cd: (c: Option.Option<number>) => Option.Option<number>, de: (d: Option.Option<number>) => number): number (+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<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 (2),
import Option Option .function andThen<(val: any) => Option.Option<number>>(fn: (val: any) => Option.Option<number>): <O1>(option: O1) => Option.OptionFor<Option.Option<number> | O1, number> (+1 overload)Chains the next computation using the value of an
Option
or
OptionAsync
.
If the input is a
None
, it is returned unchanged.
Otherwise, the provided function is called, and its result is returned as-is.
@typeParamF - The function type to chain.@exampleSome Case
import { Option } from 'byenull';
const option = Option.pipe(
Option.some(2),
Option.andThen((x) => Option.some(x * 2)),
);
// { type: 'Some', value: 4 }
@exampleNone Case (fn is never called)
import { Option } from 'byenull';
const option = Option.pipe(
Option.none(),
Option.andThen((x: number) => Option.some(x * 2)),
);
// { type: 'None' }
@exampleAsynchronous Case
import { Option } from 'byenull';
type User = { id: string; name: string };
const fetchUser = Option.fn(async (id: string) =>
fetch(`/api/users/${id}`).then((response) => response.json() as Promise<User>),
);
const option = await Option.pipe(
Option.some('u123'),
Option.andThen(fetchUser),
);
// { type: 'Some', value: User }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators andThen (val: any val => const divide: (a: number, b: number) => Option.Option<number> divide (val: any val , const divisor: number divisor )),
import Option Option .function map<Option.Option<number>, number>(fn: (a: number) => number): (option: Option.Option<number>) => Option.Option<number> (+1 overload)Applies a transformation function to the value of an
Option
or
OptionAsync
.
If the input is a
None
, it is returned unchanged.
@typeParamO - The input Option or OptionAsync.@typeParamU - The transformed value type.@exampleSome Case
import { Option } from 'byenull';
const option = Option.pipe(
Option.some(2),
Option.map((x) => x * 10),
);
// { type: 'Some', value: 20 }
@exampleNone Case (unchanged)
import { Option } from 'byenull';
const option = Option.pipe(
Option.none(),
Option.map((x: number) => x * 10),
);
// { type: 'None' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators map (const square: (a: number) => number square ),
import Option Option .function andThen<(a: number) => Option.Option<number>>(fn: (a: number) => Option.Option<number>): <O1>(option: O1) => Option.OptionFor<Option.Option<number> | O1, number> (+1 overload)Chains the next computation using the value of an
Option
or
OptionAsync
.
If the input is a
None
, it is returned unchanged.
Otherwise, the provided function is called, and its result is returned as-is.
@typeParamF - The function type to chain.@exampleSome Case
import { Option } from 'byenull';
const option = Option.pipe(
Option.some(2),
Option.andThen((x) => Option.some(x * 2)),
);
// { type: 'Some', value: 4 }
@exampleNone Case (fn is never called)
import { Option } from 'byenull';
const option = Option.pipe(
Option.none(),
Option.andThen((x: number) => Option.some(x * 2)),
);
// { type: 'None' }
@exampleAsynchronous Case
import { Option } from 'byenull';
type User = { id: string; name: string };
const fetchUser = Option.fn(async (id: string) =>
fetch(`/api/users/${id}`).then((response) => response.json() as Promise<User>),
);
const option = await Option.pipe(
Option.some('u123'),
Option.andThen(fetchUser),
);
// { type: 'Some', value: User }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators andThen (const squareRoot: (a: number) => Option.Option<number> squareRoot ),
import Option Option .function unwrap<number>(defaultValue: number): <O>(option: O & ([number] extends [Option.InferSome<O> | null | undefined] ? unknown : never)) => Option.Unwrapped<O, number, 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 (0),
)#Async Options
An asynchronous Option is represented by OptionAsync<T>, which is simply an alias for Promise<Option<T>>:
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) => Promise<Option.Option<User>> fetchUser = async (id: string id : string): interface Promise<T>Represents the completion of an asynchronous operation
Promise <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 response: Response response = await function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> fetch (`/api/users/${id: string id }`);
const const user: User | null user = (await const response: Response response .Body.json(): Promise<any> json ()) as type User = {
id: string;
name: string;
}
User | null;
return import Option Option .function some<User | null>(value: User | null): 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 | null user );
};
// fetchUser('u123') is an OptionAsync<User>Every function in byenull accepts an Option, an OptionAsync, or either one. There are no separate mapAsync-style functions.