{"id":16254,"library":"typesafe-api-call","title":"Typesafe API Call Utility","description":"typesafe-api-call is a minimalistic JavaScript library designed to streamline API interactions by enforcing typesafety and a functional programming paradigm. It abstracts away traditional exception handling, instead ensuring that every API call resolves to an explicit `APISuccess` or `APIFailure` result, compelling developers to handle both successful and unsuccessful outcomes distinctly. The library is currently on version 5.1.2 and appears to have an active release cadence, with recent patches and new features like `callWithRetries` introduced in minor versions. A key differentiator is its emphasis on functional results over exceptions, promoting predictable state management. It also integrates seamlessly with complementary tools like `type-decoder` and `type-crafter` to facilitate YAML-driven type and decoder generation, further enhancing end-to-end typesafety for API responses.","status":"active","version":"5.1.2","language":"javascript","source_language":"en","source_url":"https://github.com/sinha-sahil/typesafe-api-call","tags":["javascript","typesafe-api-caller","api-caller","typesafe-api-call","typesafe","ts-api-caller","typescript"],"install":[{"cmd":"npm install typesafe-api-call","lang":"bash","label":"npm"},{"cmd":"yarn add typesafe-api-call","lang":"bash","label":"yarn"},{"cmd":"pnpm add typesafe-api-call","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"ESM is the primary module system. While `packageJson.main` was patched in v5.1.1 for CJS compatibility, direct ESM imports are recommended for modern Node.js and bundlers.","wrong":"const APICaller = require('typesafe-api-call').APICaller;","symbol":"APICaller","correct":"import { APICaller } from 'typesafe-api-call';"},{"note":"APIResponse is a named export, not a default export. Ensure correct destructuring.","wrong":"import APIResponse from 'typesafe-api-call';","symbol":"APIResponse","correct":"import { APIResponse } from 'typesafe-api-call';"},{"note":"The library exports directly from its root. Do not attempt to import from internal paths like `/lib` as these are not stable API surfaces.","wrong":"import { APISuccess } from 'typesafe-api-call/lib';","symbol":"APISuccess","correct":"import { APISuccess } from 'typesafe-api-call';"},{"note":"For type-only imports, use `import type` to ensure they are stripped from the JavaScript output, preventing potential runtime errors in certain environments.","symbol":"APIRequest (type)","correct":"import type { APIRequest } from 'typesafe-api-call';"}],"quickstart":{"code":"import { APICaller, APIResponse, type APIRequest, APISuccess } from 'typesafe-api-call';\n\ninterface Post {\n  userId: number;\n  id: number;\n  title: string;\n  body: string;\n}\n\nconst serverEndpoint = 'https://jsonplaceholder.typicode.com';\n\nasync function getAllPosts(): Promise<APIResponse<Post[], unknown>> {\n  const apiRequest: APIRequest = {\n    url: new URL(`${serverEndpoint}/posts`),\n    method: 'GET'\n  };\n\n  // Using an anonymous function for decoding. In a real app, you'd use a dedicated decoder.\n  const apiResponse = await APICaller.call(\n    apiRequest,\n    (successResponse: unknown) => successResponse as Post[], // Simulate decoding\n    (errorResponse: unknown) => errorResponse // Error handling can also include decoding\n  );\n  return apiResponse;\n}\n\nasync function runExample() {\n  console.log('Fetching all posts...');\n  const getAllPostResult = await getAllPosts();\n\n  if (getAllPostResult instanceof APISuccess) {\n    console.log('Successfully fetched posts:', getAllPostResult.data.slice(0, 2));\n  } else {\n    console.log('Failed to fetch posts:', getAllPostResult.error);\n  }\n}\n\nrunExample();","lang":"typescript","description":"Demonstrates a basic GET API call using `APICaller`, showing how to define a request, provide decoding functions, and handle the explicit `APISuccess` or `APIFailure` result."},"warnings":[{"fix":"Upgrade to `typesafe-api-call@^5.1.1` or later to ensure proper module resolution across different environments. Prefer ESM imports where possible.","message":"Prior to version 5.1.1, users utilizing CommonJS environments or specific bundler configurations might have encountered issues resolving the main package entrypoint.","severity":"breaking","affected_versions":"<5.1.1"},{"fix":"Always check the `APIResponse` object using `if (response instanceof APISuccess)` or `if (response instanceof APIFailure)` to handle outcomes, rather than relying on `try/catch` for HTTP-level errors.","message":"This library replaces traditional `try/catch` blocks for network and API errors with a functional result pattern (`APISuccess` | `APIFailure`). Direct exception handling for API calls will bypass this pattern.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Implement robust decoding logic within the success and error callbacks passed to `APICaller.call`. Consider using complementary libraries like `type-decoder` for structured decoding.","message":"The `call` method requires two decoding functions: one for a successful API response and one for an erroneous API response. If these are not provided or implemented correctly, the `data` or `error` properties within `APISuccess` or `APIFailure` will remain `unknown`.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure that the `url` property of your `APIRequest` object is always instantiated as `new URL('your-api-endpoint')`.","message":"The `url` property in `APIRequest` strictly expects a `URL` object, not a string. Passing a string will result in a runtime TypeError.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Ensure you are using `import { APICaller } from 'typesafe-api-call';` (ESM) and have updated to `typesafe-api-call@^5.1.1` or later. Verify that `APICaller` is correctly imported and not `undefined`.","cause":"Incorrect module import, especially in CommonJS environments prior to v5.1.1, or attempting to access `call` on an undefined `APICaller`.","error":"TypeError: APICaller.call is not a function"},{"fix":"Add `import { APISuccess } from 'typesafe-api-call';` to the top of your file. Remember it's a named export.","cause":"The `APISuccess` class was not correctly imported from the `typesafe-api-call` package.","error":"ReferenceError: APISuccess is not defined"},{"fix":"Ensure your `APIResponse` is correctly typed (e.g., `APIResponse<MyDataType, ErrorType>`) and that the success/error decoding functions passed to `APICaller.call` return the expected types. The example's `(successResponse: unknown) => successResponse as Post[]` is a minimal cast; for production, implement actual type guards or decoders.","cause":"This error occurs when you attempt to access properties like `data` or `error` on the `APISuccess` or `APIFailure` instances without properly defining the type parameters (`T` and `U`) in `APIResponse<T, U>`, or without implementing the decoding functions correctly.","error":"Property 'data' does not exist on type 'unknown'."}],"ecosystem":"npm"}