Optional
A TypeScript library for optional values, providing a simple and type-safe way to handle optional values in your code. Inspired by Java's Optional class.
Installation
Install in the usual way:
npm install @guyroyse/optional --save
Quick Start
import Optional from '@guyroyse/optional'
const hello: string | null = readHello()
const maybeHello = Optional.ofNullable<string>(hello)
if (maybeHello.isPresent()) {
const certainlyHello = maybeHello.get()
}
const maybeNotHello = maybeHello.orElse('Goodbye')
Usage
There are three ways to create an Optional. You can explicitly create it with a value, create it as an empty value (i.e. null), or create it with a value that might be null.
const some = Optional.of<number>(42)
const none = Optional.empty<number>()
const maybe = Optional.ofNullable<number>(nullishOrNumber)
Once you have an Optional, you have a few choices:
const status = maybe.isPresent() ? 'it there' : 'it null'
const status = maybe.isEmpty() ? 'it null' : 'it there'
const value = maybe.get()
const value = maybe.orElse(23)
const value = maybe.orElseThrow(new MyError())
maybe.ifPresent(() => console.log('it there'))
maybe.ifEmpty(() => console.log('it null'))
Contributing
Feel free to send PRs for bugs or new features. Or open an issue and make me do it!