{"id":12253,"library":"typescript-result","title":"TypeScript Result Type for Error Handling","description":"The `typescript-result` package provides a robust, type-safe `Result` type, inspired by Rust's `Result` enum, for managing operations that can succeed or fail without relying on traditional `try-catch` blocks or throwing exceptions. It aims to transform chaotic error handling into elegant, functional code by enforcing explicit error handling at compile time. The current stable version is 3.5.2, with active development indicated by recent beta releases (e.g., v3.6.0-beta.3) that frequently introduce new features and fixes. Key differentiators include explicit `Ok` and `Err` variants, methods like `isOk()`, `isError()`, `map()`, `mapErr()`, and the recently added `match()` for basic pattern matching on error types. It targets modern Node.js environments (`>=18`) and is designed for seamless integration into TypeScript projects, improving code predictability and maintainability compared to implicit exception propagation.","status":"active","version":"3.5.2","language":"javascript","source_language":"en","source_url":"https://github.com/everweij/typescript-result","tags":["javascript","result","type","TypeScript","ts","error","error handling","exception","ok","typescript"],"install":[{"cmd":"npm install typescript-result","lang":"bash","label":"npm"},{"cmd":"yarn add typescript-result","lang":"bash","label":"yarn"},{"cmd":"pnpm add typescript-result","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The library primarily uses ES Modules. Use named imports for core types and constructors. CommonJS `require()` may lead to issues in modern environments or bundling.","wrong":"const { Result, Ok, Err } = require('typescript-result')","symbol":"Result","correct":"import { Result, Ok, Err } from 'typescript-result'"},{"note":"`Ok` is a class constructor for the success variant, typically imported as a named export. It's not a default export or a lowercase helper.","wrong":"import { ok } from 'typescript-result'","symbol":"Ok","correct":"import { Ok } from 'typescript-result'"},{"note":"`fromAsyncCatching` is a static method on the `Result` class, not a standalone export. Access it via `Result.fromAsyncCatching`.","wrong":"import { fromAsyncCatching } from 'typescript-result'","symbol":"fromAsyncCatching","correct":"import { Result } from 'typescript-result'; const asyncOp = Result.fromAsyncCatching(async () => {...});"}],"quickstart":{"code":"import { Result, Ok, Err } from 'typescript-result';\n\ninterface User { id: string; name: string; }\n\n// Simulate a database operation that might fail\nasync function getUserById(id: string): Promise<Result<User, Error>> {\n  return new Promise(resolve => {\n    setTimeout(() => {\n      if (id === '123') {\n        resolve(Ok({ id: '123', name: 'Alice' }));\n      } else if (id === 'error') {\n        resolve(Err(new Error('Database error: Failed to fetch user.')));\n      } else {\n        resolve(Err(new Error('User not found.')));\n      }\n    }, 100);\n  });\n}\n\nasync function processUser(userId: string) {\n  const userResult = await getUserById(userId);\n\n  if (userResult.isOk()) {\n    console.log(`Successfully fetched user: ${userResult.value.name}`);\n    // Further processing with userResult.value\n  } else {\n    console.error(`Failed to fetch user: ${userResult.error.message}`);\n    // Handle specific errors using match() available since v3.5.0\n    userResult\n      .match()\n      .when(Error, (err) => {\n        if (err.message.includes('not found')) {\n          console.warn('User ID not recognized.');\n        } else {\n          console.error(`Unhandled error type: ${err.message}`);\n        }\n      })\n      .run();\n  }\n}\n\nprocessUser('123'); // Success\nprocessUser('456'); // User not found\nprocessUser('error'); // Database error","lang":"typescript","description":"Demonstrates asynchronous `Result` usage, basic error checking with `isOk()`, accessing `value` or `error`, and handling different error types using the `match()` method."},"warnings":[{"fix":"Use `if (result.isOk()) { ... } else { ... }` blocks or methods like `result.mapErr(() => ...)` and `result.match().when(...)` to safely handle both success and error cases.","message":"Calling `unwrap()` or `expect()` on an `Err` result will throw a runtime error, bypassing the type-safety benefits of the Result type. Always check `isOk()` or use safe methods like `mapErr()`, `andThen()`, `orElse()`, or `match()` to handle the error variant explicitly.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Upgrade to `typescript-result@3.5.2` or higher to ensure that errors within error transformation callbacks are properly caught and encapsulated within the `Err` variant.","message":"Prior to v3.5.2, the static methods `Result.try` and `Result.fromAsyncCatching` might not have caught exceptions thrown *inside* their error transformation callbacks (the `errorFn` argument). This could lead to uncaught exceptions escaping the `Result`'s handling mechanism.","severity":"breaking","affected_versions":"<3.5.2"},{"fix":"Update to `typescript-result@3.4.1` or later if you are using generators with `Result` types to ensure correct functionality. Manual iteration or workarounds were necessary on older versions.","message":"Before v3.4.1, using generator syntax (`yield*`, `async function*`) with `Result` types could fail due to an incorrect `@internal` annotation on the `[Symbol.iterator]()` method, preventing proper iteration.","severity":"gotcha","affected_versions":"<3.4.1"},{"fix":"Upgrade to `typescript-result@3.5.1` or later. If upgrading isn't immediately possible, explicit type assertions (`as Result<T, E>`) might be necessary to guide the TypeScript compiler.","message":"Prior to v3.5.1, TypeScript's inference engine could struggle with `Result` types when the underlying success `value` had a structural shape that overlapped with the `Result` type itself (e.g., an object with an `ok` or `error` property). This could lead to incorrect type narrowing.","severity":"gotcha","affected_versions":"<3.5.1"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Always use `if (result.isOk()) { /* access result.value */ }` or other safe methods (`map`, `andThen`, `match`) to ensure you are operating on an `Ok` variant.","cause":"Attempting to access the `value` property on a `Result` that is an `Err` variant without first checking its type.","error":"Property 'value' does not exist on type 'Err<any>'"},{"fix":"Ensure that the variable you are calling `unwrap()` on is indeed a `Result` instance. In TypeScript, this is usually caught at compile-time. If it's a valid `Result` but `Err`, the error will be `Error: Called unwrap() on an Err value`.","cause":"This typically occurs in JavaScript (runtime) when `unwrap()` is called on a `Result` instance that is actually `undefined` or `null`, often due to a preceding operation failing silently or not returning a `Result` as expected.","error":"TypeError: Cannot read properties of undefined (reading 'unwrap')"},{"fix":"Refactor your code to explicitly handle the `Err` case using `isOk()`, `mapErr()`, `orElse()`, or `match()` before attempting to access the successful `value`. Only use `unwrap()` when you are absolutely certain the `Result` will always be `Ok` (e.g., after validation).","cause":"The `unwrap()` method was invoked on a `Result` instance that contained an error (`Err` variant). This is by design to explicitly throw if an error is unhandled.","error":"Error: Called unwrap() on an Err value"},{"fix":"Switch to ES Module import syntax: `import { Result } from 'typescript-result';`. Ensure your project's `package.json` has `\"type\": \"module\"` or use a bundler that transpiles correctly.","cause":"Attempting to import `typescript-result` using CommonJS `require()` syntax in an environment configured for ES Modules, or when the library itself is primarily ESM.","error":"Error: [ERR_REQUIRE_ESM]: require() of ES Module ... not supported. Instead change the require of ... to a dynamic import()"}],"ecosystem":"npm"}