Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to augment TypeScript interface in d.ts

Tags:

typescript

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.

like image 934
Borek Bernard Avatar asked Feb 16 '17 00:02

Borek Bernard


People also ask

What is D TS in TypeScript?

d. ts files. Those files are called declaration files and provide typescript type information about APIs of a package.

How do I combine two interfaces in TypeScript?

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.

What is declare module in TypeScript?

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.


1 Answers

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.

like image 64
artem Avatar answered Oct 26 '22 08:10

artem