You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为request-promise-native扩展自定义方法?TypeScript报错求助

Fixing "getCached is not a function" Error When Extending request-promise-native in TypeScript

Let's break down why you're hitting this error and fix it step by step. The core issue is a mismatch between your type augmentation target and how you're interacting with the library, plus a mix of CommonJS and ES module syntax that's throwing off TypeScript's type inference.

Step 1: Correct the Module Augmentation

Your current type declaration targets request's RequestAPI interface, but it needs to properly align with the actual instance you're extending. Here's the fixed augmentation:

import * as req from 'request';
import 'request-promise-native';

// Augment the request module's RequestAPI to include your custom method
declare module 'request' {
  interface RequestAPI<
    TRequest extends req.Request,
    TOptions extends req.CoreOptions,
    TUriUrlOptions
  > {
    getCached(): number;
  }
}

This explicitly tells TypeScript that the default export from request (which includes request-promise-native's promisified extensions) now has a getCached method.

Step 2: Standardize Import/Export Syntax

Mixing require() and import can cause type inconsistencies. Switch to consistent ES module syntax:

// Replace const req = require('request'); with:
import * as req from 'request';
import 'request-promise-native';

// ... your corrected type augmentation here ...

// Implement your custom method
req.getCached = function () {
  // Add your specific logic here
  return 42; // Example return value
};

// Export the extended instance
export default req;

Step 3: Validate Your TypeScript Config

Double-check your tsconfig.json to ensure these settings are present (they help TypeScript resolve types correctly):

  • "esModuleInterop": true (smoothly handles default exports between CommonJS and ES modules)
  • "module": "commonjs" (ideal for Node.js environments)
  • "typeRoots": ["./node_modules/@types", "./src/types"] (ensures custom type augmentations are detected)

Alternative: Augment request-promise-native Directly

If you're primarily using request-promise-native instead of raw request, you can augment its module directly:

import * as rp from 'request-promise-native';

declare module 'request-promise-native' {
  interface RequestPromiseAPI {
    getCached(): number;
  }
}

rp.getCached = function () {
  // Your custom logic here
  return 123;
};

export default rp;

This works because request-promise-native exports a RequestPromiseAPI interface that extends request's core functionality, so adding your method here ensures TypeScript recognizes it immediately.


内容的提问来源于stack exchange,提问作者jagan boddupalli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:41:47