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:

My related project

Timeline Creator

Create and export timeline graphs using an online tool

Information

The official (and only) TypeScript specification or grammar was outdated for a few years and was finally removed in 2020. There are no plans to update the specification.

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:

0 0 votes
Article Rating

Want more?

Share!

Subscribe
Notify of
guest
2 Comments
Inline Feedbacks
View all comments
AffiliateLabz
2 years ago

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

Dai Software
1 year ago

The blog is absolutely fantastic! Lot of great information which can be helpful about benefits of developing website. Keep updating the blogs.
 custom on-demand app development

2
0
Would love your thoughts, please comment.x
()
x