TypeScript Optional
Optional (like Java) implementation in TypeScript
Overview
Optional<T>
is a type which may contain a payload of type T
or may not contain.
It provides the common interface regardless of an instance is present or is empty.
This module reffers to Optional class in Java 8.
Install
npm install --save typescript-optional
Usage
import
import Optional from 'typescript-optional';
creating Optional<T>
objects
let nullableString: string | null = ;
let optional = Optional.ofNullable(nullableString);
let optionalPresent1 = Optional.ofNullable("foo");
let optionalPresent2 = Optional.ofNonNull("foo");
let optionalEmpty1: Optional<string> = Optional.empty();
let optionalEmpty2 = Optional.empty<string>();
operations
let optional: Optional<string> = Optional.ofNullable( );
optional.get();
optional.isPresent
optional.isEmpty
optional.ifPresent(value => console.log(value));
optional.filter(value => value.length > 0);
optional.map(value => value.length);
let powerIfPositive: (x: Number) => Optional<Number>
= x => (x > 0) ? Optional.ofNonNull(x * x) : Optional.empty();
optional.flatMap(value => powerIfPositive(value));
optional.orElse("bar");
optional.orElseGet(() => "bar");
optional.orElseThrow(() => new Error());
License
MIT License - LICENSE.md