Option represents an optional value: every Option is either Some, and contains a value, or None, and it's empty.
It is commonly used to represent the result of a function that may not return a value due to failure or missing data, such as a network request, a file read, or a database query.
Constructor
some
Constructs a SomeOption, representing an optional value that exists.
Returns a function that asserts that a value passes the test implemented by the provided function, creating an Option.Some narrowing down the value to the provided type predicate if the predicate is fulfilled. If the test fails, returns an Option.None instead.
This method offers improved type inference for the function's return value and guarantees that the function will always return an Option.
Declare a function that always returns an Option.
import { Option } from 'funkcia';
// When defining a normal function allowing typescript to infer
// the return type, sometimes the return type will be
// a union of `Option<T>` and `Option<U>` or `Option<never>`
function hasAcceptedTermsOfService(user: User) {
if (typeof user.termsOfService !== 'boolean')
return Option.none();
return user.termsOfService
? Option.some('ACCEPTED' as const)
: Option.some('DECLINED' as const);
}
// ┌─── Option<'ACCEPTED'> | Option<'DECLINED'> | Option<never>
// â–¼
const option = hasAcceptedTermsOfService(user);
// When using the `fun` method, the return type is always `Option<T | U>`
const improvedHasAcceptedTermsOfService = Option.fun(hasAcceptedTermsOfService);
// ┌─── Option<'ACCEPTED' | 'DECLINED'>
// â–¼
const option = improvedHasAcceptedTermsOfService(user);
enhance
Converts a function that may throw or return a nullable value to an enhanced function that returns an Option.
Applies a callback function to the value of the Option when it is Some, and returns the new value. Similar to chain (also known as flatMap), with the difference that the callback must return an Option, not a raw value.
import { Option } from 'funkcia';
declare function readFile(path: string): Option<string>;
declare function parseJsonFile(contents: string): Option<FileContent>;
// ┌─── Option<FileContent>
// â–¼
const option = readFile('data.json').andThen(parseJsonFile);
filter
Asserts that the Option value passes the test implemented by the provided function. If the test fails, the value is filtered out of the Option, returning a None instead.
Combines two Options into a single Option containing a tuple of their values, if both Options are Some variants, otherwise, returns None.
import { Option } from 'funkcia';
const first = Option.some('hello');
const second = Option.some('world');
// ┌─── Option<[string, string]>
// â–¼
const strings = first.zip(second);
// Output: Some(['hello', 'world'])
zipWith
Combines two Options into a single Option. The new value is produced by applying the given function to both values, if both Options are Some variants, otherwise, returns None.
import { Option } from 'funkcia';
const first = Option.some('hello');
const second = Option.some('world');
// ┌─── Option<string>
// â–¼
const greeting = first.zipWith(second, (a, b) => `${a} ${b}`);
// Output: Some('hello world')
match
Compare the Option against the possible patterns and then execute code based on which pattern matches.
import { Option } from 'funkcia';
// ┌─── User
// â–¼
const user = Option.some(databaseUser).unwrap();
const team = Option.none().unwrap();
// Output: Uncaught exception: 'called "Option.unwrap()" on a "None" value'
unwrapOr
Unwraps the Option value.
If the Option is None, returns the result of the provided callback.
Calls the function with the Option value, then returns the Option itself.
The return value of the provided function is ignored. This allows "tapping into" a function sequence in a pipe, to perform side effects on intermediate results
import { Option } from 'funkcia';
declare function findUserById(id: string): Option<User>;
const user = findUserById('user_123');
if (user.isSome()) {
return user.unwrap(); // `unwrap` will not throw
}
isNone
Returns true if the Option is empty.
import { Option } from 'funkcia';
declare function findUserByEmail(email: string): Option<User>;
const user = findUserByEmail(data.email);
if (user.isNone()) {
return await createUser(data);
}
return user.unwrap();
equals
By default, it uses referential equality to compare the values, but you can provide a custom equality function for more complex cases.
Compares the Option with another Option and returns true if they are equal.