#Checking Options
How can we look inside the actual value of an Option? Because an Option is a discriminated union, checking the type with a type guard narrows the type so value is available without a cast.
#Checking for a Some with isSome
isSome returns true when the Option holds a value, and narrows the type in the branch:
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 user: Option.Option<User> user = const findUser: (id: string, users: User[]) => Option.Option<User> findUser ("u1", const users: User[] users );
if (import Option Option .function isSome<Option.Option<User>>(option: Option.Option<User>): option is Option.Some<User>Type guard to check if an
Option
is a
Some
.
@typeParamO - The Option type to check.@paramoption - The Option to check.@returnstrue if the option is a Some, otherwise false.@exampleimport { Option } from 'byenull';
declare const option: Option.Option<number>;
if (Option.isSome(option)) {
console.log(option.value); // number
}
@categoryType Guards isSome (const user: Option.Option<User> user )) {
var console: Console console .Console.log(...data: any[]): voidThe console.log() static method outputs a message to the console.
log (const user: Option.Some<User> user .value: User value ); // { id: 'u1', name: 'Alice' }
} else {
var console: Console console .Console.log(...data: any[]): voidThe console.log() static method outputs a message to the console.
log ("No such user");
}Inside the if branch, TypeScript knows the Option is a Some, so user.value is the User.
#Checking for a None with isNone
isNone is the flip side of the coin. It narrows to the variant without a value:
const const user: Option.Option<User> user = const findUser: (id: string, users: User[]) => Option.Option<User> findUser ("u404", [{ id: string id : "u1", name: string name : "Alice" }]);
if (import Option Option .function isNone<Option.Option<User>>(option: Option.Option<User>): option is Option.NoneType guard to check if an
Option
is a
None
.
@typeParamO - The Option type to check.@paramoption - The Option to check.@returnstrue if the option is a None, otherwise false.@exampleimport { Option } from 'byenull';
declare const option: Option.Option<number>;
if (Option.isNone(option)) {
console.log('No value present');
}
@categoryType Guards isNone (const user: Option.Option<User> user )) {
var console: Console console .Console.log(...data: any[]): voidThe console.log() static method outputs a message to the console.
log ("User not found"); // this branch runs
}#Both guards work on our project
Let's combine the guards to render a profile, the first place our lookup produces something visible:
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 const displayName: (id: string) => string displayName = (id: string id : string): string => {
const const user: Option.Option<User> user = const findUser: (id: string, users: User[]) => Option.Option<User> findUser (id: string id , const users: User[] users );
if (import Option Option .function isNone<Option.Option<User>>(option: Option.Option<User>): option is Option.NoneType guard to check if an
Option
is a
None
.
@typeParamO - The Option type to check.@paramoption - The Option to check.@returnstrue if the option is a None, otherwise false.@exampleimport { Option } from 'byenull';
declare const option: Option.Option<number>;
if (Option.isNone(option)) {
console.log('No value present');
}
@categoryType Guards isNone (const user: Option.Option<User> user )) {
return "Guest";
}
const const profile: Option.Option<Profile> profile = const findProfile: (userId: string, profiles: Profile[]) => Option.Option<Profile> findProfile (const user: Option.Some<User> user .value: User value .id: string id , const profiles: Profile[] profiles );
if (import Option Option .function isSome<Option.Option<Profile>>(option: Option.Option<Profile>): option is Option.Some<Profile>Type guard to check if an
Option
is a
Some
.
@typeParamO - The Option type to check.@paramoption - The Option to check.@returnstrue if the option is a Some, otherwise false.@exampleimport { Option } from 'byenull';
declare const option: Option.Option<number>;
if (Option.isSome(option)) {
console.log(option.value); // number
}
@categoryType Guards isSome (const profile: Option.Option<Profile> profile ) && const profile: Option.Some<Profile> profile .value: Profile value .displayName?: string | undefined displayName !== var undefined undefined ) {
return const profile: Option.Some<Profile> profile .value: Profile value .displayName?: string displayName ;
}
return const user: Option.Some<User> user .value: User value .name: string name ;
};
const displayName: (id: string) => string displayName ("u1"); // 'Alice A.'
const displayName: (id: string) => string displayName ("u2"); // 'Bob', no profile, falls back to the name
const displayName: (id: string) => string displayName ("u404"); // 'Guest', no user at allThis works, but the code is messy: multiple if blocks that guard execution, nested lookups, and the absence-handling are mixed into the happy path. It's hard to read what the logic of the function is.
The next chapters will replace this imperative code block with a single composed pipeline.