Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript interface, function and namespace all have the same name. Which is being exported?

In the Typescript definition file (DefinitelyTyped) I am examining, there is an interface, a function and a namespace all with the exact same name: twilio.

Here is the sample, from the first few lines of the file:

declare interface twilio {
  (sid?: string, tkn?: string, options?: twilio.ClientOptions): twilio.RestClient
}

declare function twilio(sid?: string, tkn?: string, options?: twilio.ClientOptions): twilio.RestClient;

declare namespace twilio {
 ....

Then all the way at the bottom of the file it says

export = twilio;

Well which one is it exporting? The interface? The function? the namespace? How does this make any sense? How can you name multiple things the exact same nae in the same scope/namespace ??

like image 414
CodyBugstein Avatar asked Jan 18 '18 05:01

CodyBugstein


2 Answers

The official typescript doc calls this "declaration merging".

like image 155
ppp Avatar answered Sep 27 '22 16:09

ppp


Expand @ppp answer

Declaration merging is when the TypeScript complier merges two or more types into one declaration provided they have the same name.

Important thing to remember is: class with class cannot be merged.

So just for example is allowed to merge:

interface User {
  name: string;
}

interface User {
  age: number;
}

interface User {
  height: number;
}

class Person implements User {
  name = "John"
  age = 30;
  height = 180
}

enum User {...}

namespace User {...}

const person = new Person();
console.log(person) // {name: "John", age: 30, height: 180}

export person;

So to answer to your question you can export single type like in the example above the rest of the declaration are merged between them

like image 20
Gianfabio Pezzolla Avatar answered Sep 27 '22 17:09

Gianfabio Pezzolla