Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the purpose of "export as namespace foo"?

Tags:

typescript

I'm using some *.d.ts files and I see in many of them the following two lines:

//foo.d.ts
export = foo;
export as namespace foo;

declare var foo;

[...]

I can understand that in the former one (export = foo), foo is the thing exported. But what is the meaning of export as namespace foo? How should it be consumed or used from the outside?

In the case of react ambient declaration file, it says:

export = React;
export as namespace React;

declare namespace React {
[...]

Can't the React namespace be exported with:

export declare namespace React { [...]

?

like image 714
Daniel San Avatar asked Jun 14 '17 21:06

Daniel San


1 Answers

Here is what I have understand based on this doc: https://www.typescriptlang.org/docs/handbook/modules.html#umd-modules

When you write export as namespace React; in a declaration file (*.d.ts) you are telling that React can be used to access the whole exported content as a global variable inside a script file.

A script file is a typescript file without export or import, so it can be used for example within a <script src="yourFile.js"> inside a browser.

Note that this only works if you also export something, in this case export = React tells to export the namespace.

export declare namespace React is not equivalent because for commonJs it doesn't export as the default and for script file it just doesn't work (doesn't add the namespace to the global variables).

For you own module if you expect to use only commonjs I suggest to avoid using namespaces and just use export ... or export default ... if you have just one export.

See also:

  • https://stackoverflow.com/a/44849515/209727
  • https://www.typescriptlang.org/docs/handbook/namespaces.html
like image 82
2 revs, 2 users 97% Avatar answered Nov 05 '22 08:11

2 revs, 2 users 97%