{"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,"search_vec":"'2.0.0':85 '2.0.1':62,94 '3.0.0':65 '8':16 'abandon':88 'absenc':28 'activ':73 'aim':40 'alpha.3':66 'api':52,111 'avail':71 'back':125 'check':38 'class':19 'compar':146 'convers':124 'core':135 'counterpart':150 'current':58 'cycl':81 'deploy':91 'design':20 'develop':23,74 'differenti':98 'direct':105 'due':89 'e.g':112 'easi':123 'equal':143 'explicit':138 'fluent':51 'focus':132 'function':137 'handl':54 'help':22 'implement':8 'includ':99 'indic':72 'inspir':13,106 'irregular':79 'ispres':113 'issu':92 'java':15,108,149,152 'javascript':47,128,151 'key':97 'like':118,142 'manag':24 'map':114 'method':117,141 'miss':140 'nativ':127 'note':139 'null':35 'nullabl':55,129 'nullpointerexcept':43 'option':2,5,11,18,110,136,153 'orels':115 'ornul':119 'orundefin':121 'packag':76 'pre':68 'pre-releas':67 'presenc':26 'previous':84 'provid':6,49 'reduc':42 'releas':69,80,86 'resort':33 'seen':78 'stabil':95 'stabl':59 'strong':101 'though':63 'tostr':145 'type':12,102,130 'typeerror':45 'typescript':1,4,104,154 'typescript-opt':3 'undefin':37 'valu':31,56 'version':60 'without':32","created_at":"2026-04-19T13:42:10.760327+00:00","updated_at":"2026-04-19T13:42:10.760327+00:00","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","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null,"type":"library","homepage":null,"github":"https://github.com/bromne/typescript-optional","docs":null,"changelog":null,"pypi":null,"npm":"https://www.npmjs.com/package/typescript-optional","openapi_spec":null,"status_page":null,"smithery":null,"categories":["serialization"],"base_url":null,"auth_type":null,"provenance":{"verified_status":null,"verified_at":null,"last_verified":"2026-06-17","next_check":"2026-07-18","install_tag":null}}