In this post, we will explore ambient modules in TypeScript. We will cover what ambient modules are, how to use them, and some caveats and tips when working with them.
What are ambient modules?
d.ts file format.
TypeScript ecosystem contains thousands of such ambient declarations files available to you via DefinitelyTyped . DefinitelyTyped is a repository that contains declaration files contributed and maintained by the TypeScript community.
If you’ve ever installed types in your projects using commands like this:
npm install --save-dev @types/node
Then you’ve used DefinitelyTyped.
How to use ambient modules
There are three main ways to use declaration modules in TypeScript:
- Importing declaration using triple-slash directive.
A triple-slash directive is a single-line comment with an XML tag instructing the compiler to include additional files in the compilation process. It usually looks something like this:
/// <reference path="../types/sample-module/index.d.ts" />
Note: The single-slash directives must be located at the top of the file. If you put it below the
import statements, it will be treated as a regular comment instead.
field in the
tsconfig file is used to specify directories that contain declaration files. The compiler will search these directories for TypeScript declaration files to include in the compilation process.
Note: The directories you specify are relative to the placement of the
The paths field in the
tsconfig file specifies specific paths where TypeScript should look for TypeScript files based on the regex pattern you provide.
Tips when working with ambient modules:
Use paths to add customized type definitions to your project.
If you want to use your customized type definitions for a module that has its own type definitions, you can override the compiler option by adding a tweak to
As a result, TypeScript will use the types coming from your custom module rather than the ones provided by the external library.
How you declare your imports makes a difference
It is important to place all import declarations inside the module declaration when creating TypeScript definitions for third-party libraries.
Otherwise, your declaration module will be treated as an
instead, and your custom types will not be registered.
The above won’t work. You need to declare your imports inside of the module instead:
Fix your types quickly using shorthand ambient declaration
If you don’t want to spend the time creating declarations to be able to use the third-party library code, you can use a
shorthand module declaration
declare module "sample-module";
When using a shorthand ambient declaration, all imports from that module will be of the type
In this post, we covered what ambient modules are and how to use them. We also listed some tips for when working with them. Hope you found this post helpful!
If you’d like to get more web development, React and TypeScript tips consider
following me on Twitter
, where I share things as I learn them.