TypeScript – Ambient Namespaces in Declaration Files

TypeScript – Ambient Namespaces in Declaration Files

I don’t want to create a guide on the declaration files but only share some tips: what is an ambient declaration, what’s specific about ambient namespaces and what is the result of using ambient namespaces.

Ambient declaration

An ambient module, class, namespace, etc. – is the one without implementation; implementation is provided elsewhere. These members are not added to the compiled application and are used only for providing type information for syntax checking or intellisense.

Ambient members are created by prepending them with declare.

Documentation:

Ambient namespace

What is special about ambient namespace (created by typing declare namespace) is the fact that all its members are exported by default. There is no need to include the export keyword for its members.

Documentation:

Except for ImportAliasDeclarations, AmbientNamespaceElements always declare exported entities regardless of whether they include the optional export modifier.

Example: namespace without export

Declaration file for a library:

TypeScript
lib.d.ts

Usage in your application:

JS
app.js

Example: namespace with export

Declaration file for a library:

TypeScript
lib.d.ts

Usage in your application:

JS
app.js

Example: no namespace

Declaration file for a library:

TypeScript
lib.d.ts

Usage in your application:

JS
app.js

Summary

Depending on your requirement on the usage of your lib, you should select the appropriate declaration file syntax. Although the option to have the members (e.g. functions) available in the global namespace without import may be more comfortable in some cases, it pollutes the global namespace and introduces some confusion.

Below are some examples of libraries that provide global functions, with links to their definition types:

The official documentation by TypeScript and DefinitelyTyped is somewhat vague, but useful nonetheless:

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
AffiliateLabz Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
AffiliateLabz
Guest

Great content! Super high-quality! Keep it up! 🙂