Type Option represents an optional value: every Option is either Some and contains
a value, or None, and does not. It can be a useful substitute for null due to it's
functional nature that brings less errors and needs less checks.
functiondivide(numerator: number, denominator: number) => Option<number> {
return denominator == 0.0
? None()
: Some(numerator / denominator);
}
// The return value of the function is an optionconst result = divide(2.0, 3.0);
// Pattern match to retrieve the value
result.match({
// The division was valid
Some: x => console.log('Result: ', x),
// The division was invalid
None: () => console.log('Cannot divide by 0'),
});
Type Option represents an optional value: every Option is either Some and contains a value, or None, and does not. It can be a useful substitute for
null
due to it's functional nature that brings less errors and needs less checks.function divide(numerator: number, denominator: number) => Option<number> { return denominator == 0.0 ? None() : Some(numerator / denominator); } // The return value of the function is an option const result = divide(2.0, 3.0); // Pattern match to retrieve the value result.match({ // The division was valid Some: x => console.log('Result: ', x), // The division was invalid None: () => console.log('Cannot divide by 0'), });
Examples
Basic pattern matching on Option:
const msg = Some('howdy'); // Get the value contained by option const unwrappedMsg = msg.unwrapOr('default message');
Initialize a result to None before a loop:
type Kingdom = {type: 'Plant'|'Animal', size: number, name: string}; const allTheBigThings: [Kingdom] = [ {type: 'Plant', size: 250, name: 'redwood'}, {type: 'Plant', size: 230, name: 'noble fir'}, {type: 'Plant', size: 229, name: 'sugar pine'}, {type: 'Animal', size: 25, name: 'blue whale'}, {type: 'Animal', size: 19, name: 'fin whale'}, {type: 'Animal', size: 15, name: 'north pacific right whale'} ]; // We're going to search for the name of the biggest animal, // but to start with we've just got `None`. let nameOfBiggestAnimal: Option<string> = None(); let sizeOfBiggestAnimal = 0; for (const {type, size, name} of allTheBigThings) { if (type === 'Plant') { continue; } if (size > sizeOfBiggestAnimal) { sizeOfBiggestAnimal = size; nameOfBiggestAnimal = Some(name); } } nameOfBiggestAnimal.match({ Some: name => console.log(`the biggest animal is ${name}`); None: () => console.log('there are no animals :('); });