simple-optional
v1.1.0
Published
Simplified Optional container inspired by Java 8 implementation.
Downloads
2
Maintainers
Readme
Simple Optional
A lightweight TypeScript implementation of an Optional container (inspired by Java's Optional). Encapsulates a value that may be present or absent, and provides helpers for safe access and transformations.
Features
- Create present, nullable, or empty optionals
- Check presence with
isPresent()/isEmpty() - Safe retrieval with
get(),orElse(), andorElseThrow() - Transform values with
map() - Conditional execution with
ifPresent()
Usage
Import or include the class in your project, then:
- Create an Optional with a non-null value:
const o = Optional.of(42);- Create an Optional that may be null:
const maybe = Optional.ofNullable<number>(null);- Create an empty Optional:
const empty = Optional.empty<number>();- Check presence:
if (o.isPresent()) { /* ... */ }
if (empty.isEmpty()) { /* ... */ }- Execute when present:
o.ifPresent(v => console.log(v));- Transform a value:
const str = Optional.of(5).map(n => 'Number ' + n); // Optional<string>- Retrieve value with default or throw:
const x = maybe.orElse(10);
const y = maybe.orElseThrow(() => new Error('Missing value'));Error handling
Errors are thrown as Error instances with class-prefixed messages, e.g. [Optional] No value present.
Notes & assumptions
of()andset()treat bothnullandundefinedas invalid.ofNullable()intentionally allowsnullto represent emptiness.- The class uses a private constructor—use static factories to create instances.
