Ambient modules are a powerful feature in TypeScript that allow developers to describe the shape of external libraries or modules without actually implementing their functionality. They provide type information for modules that may not have been written in TypeScript originally.
The main purposes of ambient modules are:
To create an ambient module, you use the declare
keyword followed by module
. Here's a basic example:
// myModule.d.ts
declare module "my-module" {
export function someFunction(): void;
export const someValue: number;
}
This declaration file (.d.ts
) tells TypeScript about the shape of the "my-module" module without providing an implementation.
Once you've declared an ambient module, you can use it in your TypeScript code as if it were a regular module:
import { someFunction, someValue } from "my-module";
someFunction();
console.log(someValue);
TypeScript will now provide type checking and autocompletion for the imported module.
.d.ts
filesYou can also create wildcard module declarations for a group of modules:
declare module "my-library-*" {
export function helper(): void;
}
This declaration will match any import that starts with "my-library-".
Ambient modules can also be used to augment existing modules:
// augmentation.d.ts
import * as React from 'react';
declare module 'react' {
interface Component {
customMethod(): void;
}
}
This example adds a customMethod
to React's Component
interface.
Ambient modules are a crucial feature in TypeScript for working with external libraries and ensuring type safety across your project. By mastering ambient modules, you can enhance your development experience and catch potential errors early in the development process.
For more information on working with external libraries in TypeScript, check out our guide on Using Third-Party Libraries.