My use case: request's RequestResponse type definition is missing the body
property and looks like this:
declare namespace request {
// ...
export interface RequestResponse extends http.IncomingMessage {
request: Options;
}
// ...
}
declare var request: request.RequestAPI<request.Request, request.CoreOptions, request.RequiredUriUrl>;
export = request;
I'm trying to fix it by creating a request-fix.d.ts
file with something like this:
import * as http from 'http';
declare namespace request {
export interface RequestResponse extends http.IncomingMessage {
body: any;
}
}
But it has no effect. My end goal is that in my app.ts
, I can do this:
import * as rp from 'request-promise';
import { RequestResponse } from 'request';
let response = rp.get(url);
response.statusCode; // works
response.body; // doesn't compile
Of course I could just contribute to DefinitelyTyped :) But this question is about to augment the RequestResponse
interface.
d. ts files. Those files are called declaration files and provide typescript type information about APIs of a package.
To merge two interfaces with TypeScript, we can use extends to extend multiple interfaces. to create the IFooBar that extends IFoo and IBar . This means IFooBar has all the members from both interfaces inside.
A module is a piece of code that can be called or used in another code. There is nothing new about modules in Typescript. The concept of the module was introduced by JavaScript with ECMAScript 2015 release. Typescript is just re-using this feature.
Here is the combination that works in request-fix.d.ts
:
import * as http from 'http';
declare module 'request' {
export interface RequestResponse extends http.IncomingMessage {
body: any;
}
}
To augment existing module, declare module
must be used instead of declare namespace
, and it must appear in the module scope somewhere among the compiled sources.
That is, request-fix.d.ts
must have some import at top level to turn it into a module, as you did with import * as http from 'http'
in your code. If declare module
appears in the non-module scope, (as I did with the first attempt at the answer), it just declares separate, unrelated module as described here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With