简体   繁体   中英

How to declare a new property for an object in an npm package?

Code:

import * as request from 'superagent';

request
    .get('https://***.execute-api.eu-west-1.amazonaws.com/dev/')
    .proxy(this.options.proxy)

TypeScript Error

Property 'proxy' does not exist on type 'SuperAgentRequest'

Type annotatations for request

(alias) namespace request
(alias) const request: request.SuperAgentStatic
import request

My attempt at type definitions (that is not successful in getting rid of the TypeScript error):

declare module superagent {
    interface SuperAgentRequest {
        proxy: any;
    }
}

What am I doing wrong in the declaration file?

First, don't forget to put doubles quotes around superagent, when you declare the module.

Assumed, you have no types to augment and declare the package from scratch, put following in its own .d.ts file like globals.d.ts:

declare module "superagent" {
  interface SuperAgentRequest {
    proxy: any;
  }

  export function get(s: string): SuperAgentRequest;
}

From a file module, you could then write:

import * as request from "superagent";

request
  // get returns request.SuperAgentRequest
  .get("https://***.execute-api.eu-west-1.amazonaws.com/dev/")
  .proxy(this.options.proxy);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM