如何为request-promise-native扩展自定义方法?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

