Const
Executes a function and wraps the result in an Optional type. If the function returns null or undefined, returns a none Optional. Otherwise, returns a some Optional with the return value.
Use optional.from_nullable()
for direct nullable values instead.
In the next major release, from()
will only accept nullable values directly
instead of invoking functions, matching the behavior of from_nullable()
.
// DEPRECATED: Current usage
const userResult = optional.from(() => findUser("123"));
const element = optional.from(() => document.getElementById('myId'));
// PREFERRED: Use from_nullable with values to avoid the function call overhead
const userResult = optional.from_nullable(findUser("123"));
const element = optional.from_nullable(document.getElementById('myId'));
// FUTURE: In next major release, from_nullable() will be renamed to from()
const userResult = optional.from(findUser("123")); // Will be the new behavior
Creates an Optional from a value that may be null or undefined. If the value is null or undefined, returns a none Optional. Otherwise, returns a some Optional with the value.
// Working with nullable values
function findUser(id: string): User | null {
return users.find(u => u.id === id) || null;
}
const user = optional.from_nullable(findUser("123"));
if (user.is_some()) {
console.log(user.value.name);
}
// Direct nullable value conversion
const maybeNumber: number | undefined = parseFloat(input);
const result = optional.from_nullable(maybeNumber);
Executes an async function and wraps the result in a Promise
// Working with async functions that might return null
async function fetchUser(id: string): Promise<User | null> {
const response = await fetch(`/api/users/${id}`);
return response.ok ? response.json() : null;
}
const userResult = await optional.from_async(() => fetchUser("123"));
if (userResult.is_some()) {
console.log(userResult.value.name);
} else {
console.log("User not found");
}
// Converting Promise-based APIs that might return null
const userData = await optional.from_async(async () => {
const response = await fetch('/api/data');
return response.ok ? await response.json() : null;
});
The
optional
namespace provides functions to create Optional instances.