{"id":15867,"library":"ts-results","title":"ts-results: Rust-like Result and Option for TypeScript","description":"ts-results is a TypeScript library that provides compile-time error checking and optional values, inspired by Rust's `Result` and `Option` enums. It offers a type-safe approach to handling fallible operations and potential absence of values without relying on exceptions or `null`/`undefined`. The current stable version, 3.3.0, was last published in 2021. This package differentiates itself by offering a lightweight, focused implementation of these core algebraic data types, in contrast to more comprehensive functional programming libraries. It enables developers to explicitly model success (`Ok`) or failure (`Err`) states and presence (`Some`) or absence (`None`) of a value, leveraging TypeScript's type system to ensure these states are handled at compile time, thereby reducing runtime errors.","status":"maintenance","version":"3.3.0","language":"javascript","source_language":"en","source_url":"https://github.com/vultix/ts-results","tags":["javascript","Rust","Result","Results","Option","Options","Typescript","TS","Ok","typescript"],"install":[{"cmd":"npm install ts-results","lang":"bash","label":"npm"},{"cmd":"yarn add ts-results","lang":"bash","label":"yarn"},{"cmd":"pnpm add ts-results","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"While 'ts-results' v3.3.0 ships with CommonJS support, ES Module imports are the standard for modern TypeScript. The original package may have issues with native ESM environments without proper configuration or a bundler.","wrong":"const Result = require('ts-results').Result","symbol":"Result","correct":"import { Result } from 'ts-results'"},{"note":"Use 'Ok' for a successful result. It can be instantiated directly as 'new Ok(value)' or as a factory function 'Ok(value)'.","wrong":"import { ok } from 'ts-results' // Case sensitive","symbol":"Ok","correct":"import { Ok } from 'ts-results'"},{"note":"Use 'Err' for a failed result. Like 'Ok', it can be instantiated as 'new Err(error)' or 'Err(error)'.","wrong":"import { error } from 'ts-results' // Incorrect name for the error variant","symbol":"Err","correct":"import { Err } from 'ts-results'"},{"note":"The Option type represents an optional value: either Some(value) or None.","wrong":"import { option } from 'ts-results'","symbol":"Option","correct":"import { Option } from 'ts-results'"},{"note":"Use 'Some' to represent the presence of a value within an 'Option'.","wrong":"import { Value } from 'ts-results' // Not a part of the API","symbol":"Some","correct":"import { Some } from 'ts-results'"},{"note":"Use 'None' to represent the absence of a value within an 'Option'.","symbol":"None","correct":"import { None } from 'ts-results'"}],"quickstart":{"code":"import { Ok, Err, Result, Some, None, Option } from 'ts-results';\nimport { readFileSync, existsSync } from 'fs';\n\n// --- Result Example: Handling file operations ---\n\nfunction readFileSafe(path: string): Result<string, 'file_not_found' | 'read_error'> {\n  if (!existsSync(path)) {\n    return new Err('file_not_found');\n  }\n  try {\n    const content = readFileSync(path, 'utf8');\n    return new Ok(content);\n  } catch (e) {\n    return new Err('read_error');\n  }\n}\n\nconst filePath = 'test.txt';\n// Simulate creating a file for the example\nrequire('fs').writeFileSync(filePath, 'Hello, ts-results world!');\n\nconst fileResult = readFileSafe(filePath);\n\nif (fileResult.ok) {\n  console.log(`File content: ${fileResult.val}`);\n} else {\n  console.error(`Error reading file: ${fileResult.val}`);\n}\n\n// --- Option Example: Handling potentially missing configuration ---\n\ninterface UserConfig {\n  theme?: string;\n  notificationsEnabled?: boolean;\n}\n\nfunction getUserTheme(config: UserConfig): Option<string> {\n  if (config.theme) {\n    return new Some(config.theme);\n  } else {\n    return None;\n  }\n}\n\nconst userSettings: UserConfig = { notificationsEnabled: true };\nconst themeOption = getUserTheme(userSettings);\n\nif (themeOption.some) {\n  console.log(`User theme: ${themeOption.val}`);\n} else {\n  console.log('User theme not set, using default.');\n}\n\n// Clean up simulated file\nrequire('fs').unlinkSync(filePath);\n","lang":"typescript","description":"Demonstrates `Result` for explicit error handling in a file read operation and `Option` for handling potentially missing user configuration values, ensuring type safety at compile time."},"warnings":[{"fix":"For active maintenance and full ES Module compatibility, consider migrating to the `ts-results-es` fork. Otherwise, ensure your build configuration correctly handles CommonJS dependencies within an ESM project, or configure your TypeScript compiler to output CommonJS.","message":"The original `ts-results` package (v3.3.0) primarily targets CommonJS modules. Using it in native ES Module environments without proper transpilation (e.g., via a bundler) may lead to import errors like 'Cannot use import statement outside a module' or 'require is not defined'.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Evaluate migrating to `ts-results-es` (e.g., `npm install ts-results-es`). Be aware of API changes in the fork (see related warning).","message":"The original `ts-results` package has not been updated since 2021 (v3.3.0). It is effectively in a maintenance state with no active development. Users seeking new features, bug fixes, or dedicated ESM support should consider the `ts-results-es` fork, which is actively maintained.","severity":"deprecated","affected_versions":">=3.3.0"},{"fix":"Update property access from `.val` to `.value` (for `Ok`/`Some`) or `.error` (for `Err`). Replace boolean checks (`.ok`, `.err`, `.some`, `.none`) with their respective method calls (`.isOk()`, `.isErr()`, `.isSome()`, `.isNone()`).","message":"If migrating from `ts-results` to the `ts-results-es` fork, be aware of API breaking changes. Direct property access like `result.val` (for `Ok` and `Some` values) and `result.val` (for `Err` errors) have been replaced by `.value` or `.error` respectively. Additionally, boolean flags like `result.ok`, `result.err`, `option.some`, `option.none` are replaced by methods such as `result.isOk()`, `result.isErr()`, `option.isSome()`, `option.isNone()`.","severity":"breaking","affected_versions":">=1.0.0 (when migrating to ts-results-es >=1.0.0)"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"1. If your project *must* be ESM, consider migrating to the `ts-results-es` fork which has explicit ESM support. 2. If staying with `ts-results`, ensure your build process (e.g., Webpack, Rollup) or TypeScript configuration (`tsconfig.json`) correctly handles CommonJS interoperability, or configure your output module system to CommonJS (`\"module\": \"CommonJS\"`). 3. For Node.js, you might need to use `require()` if not using a bundler, but this can lead to type issues.","cause":"The `ts-results` package (v3.3.0) is primarily configured as CommonJS. When a project is set up for ES Modules (`\"type\": \"module\"` in `package.json` or `.mjs` files), direct `import` statements for CJS packages can cause this error.","error":"Cannot use import statement outside a module"},{"fix":"Always use a type guard to narrow the `Result` type before accessing its value. For an `Ok` result, check `if (result.ok)` then `result.val` will be `T`. For an `Err` result, check `if (!result.ok)` (or `if (result.err)` if using the fork), then `result.val` will be `E`.","cause":"This error occurs when attempting to access `result.val` directly on an `Err` variant of a `Result<T, E>` without a preceding type guard (e.g., `if (result.ok)`), or attempting to access `result.val` on an `Ok` variant when `val` refers to the error type.","error":"Property 'val' does not exist on type 'Err<E>'"}],"ecosystem":"npm"}