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.
Table of contents
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:
By the way, I’ve put together a small collection of tools I use regularly — things like time tracking, Git helpers, database utilities, and a few others that make development a bit smoother.
- https://github.com/Microsoft/TypeScript-Handbook/issues/180
- https://github.com/Microsoft/TypeScript/blob/master/doc/spec-ARCHIVED.md#12-ambients
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:
Usage in your application:
Example: namespace with export
Declaration file for a library:
Usage in your application:
Example: no namespace
Declaration file for a library:
Usage in your application:
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:
- https://www.typescriptlang.org/docs/handbook/declaration-files/by-example.html
- https://definitelytyped.org/guides/best-practices.html
Great content! Super high-quality! Keep it up! 🙂
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