JSPM

simple-optional

1.0.1
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 96
  • Score
    100M100P100Q59726F
  • License ISC

Simplified Optional container inspired by Java 8 implementation.

Package Exports

    This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (simple-optional) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

    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(), and orElseThrow()
    • 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() and set() treat both null and undefined as invalid.
    • ofNullable() intentionally allows null to represent emptiness.
    • The class uses a private constructor—use static factories to create instances.