{"id":12246,"library":"typescript-optional","title":"TypeScript Optional","description":"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.","status":"active","version":"3.0.0-alpha.3","language":"javascript","source_language":"en","source_url":"https://github.com/bromne/typescript-optional","tags":["javascript","java","optional","typescript"],"install":[{"cmd":"npm install typescript-optional","lang":"bash","label":"npm"},{"cmd":"yarn add typescript-optional","lang":"bash","label":"yarn"},{"cmd":"pnpm add typescript-optional","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Primarily designed for ESM and TypeScript; CommonJS `require` is generally discouraged in modern TypeScript projects.","wrong":"const { Optional } = require('typescript-optional');","symbol":"Optional","correct":"import { Optional } from 'typescript-optional';"},{"note":"Using `import type` is preferred for type-only imports to prevent accidental runtime side effects or bundle size issues.","wrong":"import { Optional } from 'typescript-optional';","symbol":"Optional (type import)","correct":"import type { Optional } from 'typescript-optional';"},{"note":"Always use static factory methods like `ofNullable`, `ofNonNull`, or `empty` to create `Optional` instances, as the constructor may not be public or stable.","wrong":"new Optional(value);","symbol":"Optional.ofNullable","correct":"Optional.ofNullable(value);"}],"quickstart":{"code":"import { Optional } from \"typescript-optional\";\n\n// Example with a potentially null string\nconst userName: string | null = Math.random() > 0.5 ? \"Alice\" : null;\nconst optionalUserName: Optional<string> = Optional.ofNullable(userName);\n\nconsole.log(`Is name present? ${optionalUserName.isPresent()}`);\n\n// Using ifPresentOrElse to handle both cases\noptionalUserName.ifPresentOrElse(\n  (name) => console.log(`Hello, ${name}!`),\n  () => console.log(\"User name is not available.\")\n);\n\n// Map and filter operations\nconst nameLength: Optional<number> = optionalUserName\n  .filter((name) => name.length > 3)\n  .map((name) => name.length);\n\nnameLength.ifPresent((len) => console.log(`Name length (if > 3): ${len}`));\n\n// Providing a default value\nconst displayUserName: string = optionalUserName.orElse(\"Guest\");\nconsole.log(`Display name: ${displayUserName}`);\n\n// Converting to nullable JavaScript types\nconst rawName: string | null = optionalUserName.orNull();\nconsole.log(`Raw name (or null): ${rawName}`);","lang":"typescript","description":"Demonstrates how to import, create, and perform common operations like checking presence, conditional execution, mapping, filtering, and providing default values with the `Optional` class."},"warnings":[{"fix":"Update calls like `optional.isPresent` to `optional.isPresent()` and `optional.isEmpty` to `optional.isEmpty()`.","message":"Version 2.0.0 introduced several breaking changes, including `Optional#isPresent` and `Optional#isEmpty` changing from accessors (properties) to methods. `Optional#map` also had its type signature refined, representing that it exactly returns a value whose payload is non-null type, and `Optional.toJSON` was added.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Always check `optional.isPresent()` before calling `get()`, or use safer methods like `orElse()`, `orElseGet()`, `orElseThrow()`, `orNull()`, or `orUndefined()` to retrieve the value.","message":"The `get()` method will throw a `TypeError` if the `Optional` instance is empty (does not contain a value). This behavior is consistent with Java's `Optional.get()` but is a common source of runtime errors if not properly guarded.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Use `Optional.ofNullable(value)` instead if the value might be `null` or `undefined`. Only use `ofNonNull` when you are certain the value is not null.","message":"The static factory method `Optional.ofNonNull()` will throw a `TypeError` if the provided argument is `null` or `undefined`. It is specifically designed for situations where you expect a non-null value.","severity":"gotcha","affected_versions":">=1.8.0"},{"fix":"Upgrade to `typescript-optional@2.0.1` or a later compatible version.","message":"The `v2.0.0` release was initially abandoned due to deployment issues. While `v2.0.1` fixed these, developers targeting `v2` should ensure they use `v2.0.1` or newer to avoid potential problems.","severity":"breaking","affected_versions":"2.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Change `optional.isPresent` to `optional.isPresent()` and `optional.isEmpty` to `optional.isEmpty()`.","cause":"In `typescript-optional` v2.0.0 and later, `isPresent` (and `isEmpty`) changed from a property accessor to a method.","error":"TypeError: optional.isPresent is not a function"},{"fix":"Before calling `get()`, verify the presence of a value with `optional.isPresent()`, or use alternative methods like `orElse()`, `orElseGet()`, `orNull()`, or `orUndefined()` to safely handle empty optionals.","cause":"You attempted to call the `get()` method on an `Optional` instance that does not contain a value.","error":"TypeError: Cannot retrieve payload from empty Optional"},{"fix":"If the value might be `null` or `undefined`, use `Optional.ofNullable(value)` instead. Only use `Optional.ofNonNull()` when you are absolutely sure the value is present.","cause":"You passed `null` or `undefined` to `Optional.ofNonNull()`, which explicitly requires a non-null/non-undefined argument.","error":"TypeError: value must not be null"}],"ecosystem":"npm"}