TypeScript Optional

3.0.0-alpha.3 · active · verified Sun Apr 19

typescript-optional provides an implementation of the `Optional<T>` type, inspired by Java 8+'s `Optional` class, designed to help developers manage the presence or absence of a value without resorting to null or undefined checks. It aims to reduce `NullPointerExceptions` (or `TypeError` in JavaScript) by providing a fluent API for handling nullable values. The current stable version is 2.0.1, though a 3.0.0-alpha.3 pre-release is available, indicating active development. The package has seen irregular release cycles, with a previous 2.0.0 release being abandoned due to deployment issues before 2.0.1 stabilized it. Key differentiators include its strong typing with TypeScript, direct inspiration from Java's `Optional` API (e.g., `isPresent`, `map`, `orElse`), and methods like `orNull()` and `orUndefined()` for easy conversion back to native JavaScript nullable types. It focuses on the core `Optional` functionality, explicitly noting missing methods like `equals` or `toString` compared to its Java counterpart.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to import, create, and perform common operations like checking presence, conditional execution, mapping, filtering, and providing default values with the `Optional` class.

import { Optional } from "typescript-optional";

// Example with a potentially null string
const userName: string | null = Math.random() > 0.5 ? "Alice" : null;
const optionalUserName: Optional<string> = Optional.ofNullable(userName);

console.log(`Is name present? ${optionalUserName.isPresent()}`);

// Using ifPresentOrElse to handle both cases
optionalUserName.ifPresentOrElse(
  (name) => console.log(`Hello, ${name}!`),
  () => console.log("User name is not available.")
);

// Map and filter operations
const nameLength: Optional<number> = optionalUserName
  .filter((name) => name.length > 3)
  .map((name) => name.length);

nameLength.ifPresent((len) => console.log(`Name length (if > 3): ${len}`));

// Providing a default value
const displayUserName: string = optionalUserName.orElse("Guest");
console.log(`Display name: ${displayUserName}`);

// Converting to nullable JavaScript types
const rawName: string | null = optionalUserName.orNull();
console.log(`Raw name (or null): ${rawName}`);

view raw JSON →