This container represents an optional value. You can create a Option<T>
by calling either of the following constructors:
Some('Hello world')
None()
Option.some
is used to check if an Option contains a value or not.
- If
Option.some === true
, thenOption.value
exist. - If
Option.some === false
, thenOption.value
doesn't exist.
Todo
Map Option<T>
into a new Option<U>
.
- .map() is used to continue work on references that may point to a value or not
const helloWorld = new Some("Hello world");
// Converts Some("Hello world") → Some(11)
const helloWorldLength = helloWorld.map(helloStr => helloStr.length);
// Outputs 'Some(11)'
console.log(helloWorldLength);
Combine Option<T>
with another Option<U>
to create Option<U>
.
const helloWorld = new Some("Hello world");
// Converts Some("Hello world") → Some(11)
const helloWorldLength = helloWorld.and(helloStr => new Some(helloStr.length));
// Outputs 'Some(11)'
console.log(helloWorldLength);
Returns the internal value of Option<T>
. Throws if there is no value.
In general, because this function may throw, use of .unwrap() use is discouraged. Instead, prefer to use an if statment and check .some and handle the None
case explicitly.
- .unwrap() can be used when an
Option
is guaranteed to hold a value. - .unwrap() can be used when writing first versions of software and refactored later
const helloWorld = new Some("Hello world");
// Outputs 'Hello world'
console.log(helloWorld.unwrap());
Returns the internal value of Option<T>
if any, otherwise a default value.
const helloWorld = new Some("Hello World");
const none = new None();
// Outputs 'Hello World'
console.log(helloWorld.unwrapOr("Hello Vertical"));
// Outputs 'Hello Vertical'
console.log(none.unwrapOr("Hello Vertical"));
import { Option, Some, None } from "containers-ts";
function toNumber(s: string): Option<number> {
const number = Number(s);
if (isNaN(number)) {
return new None();
}
return new Some(number);
}
function addToString(s: string, n: number): Option<string> {
return toNumber("4").map(n => String(n + 1));
}
// Outputs: Some("8")
console.log(addToString("4", 4));
// Outputs: None
console.log(addToString("Vertical Strategy", 4));