Ambient Modules

A package that contains declaration files using the declare module syntax is called an ambient module. The main purpose of ambient modules is to provide typings for code that has been purely written in JavaScript, so that TypeScript can make use of it.

You can find a lot of ambient modules in the Definitely Typed repository which provides them under the @types namespace on the npm Registry. A very popular¹ example is the @types/node package which declares multiple modules like the buffer module:

buffer.d.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
declare module 'buffer' {
import { BinaryLike } from 'node:crypto';
import { ReadableStream as WebReadableStream } from 'node:stream/web';
export const INSPECT_MAX_BYTES: number;
export const kMaxLength: number;
export const kStringMaxLength: number;
export const constants: {
MAX_LENGTH: number;
MAX_STRING_LENGTH: number;
};
export type TranscodeEncoding = 'ascii' | 'utf8' | 'utf16le' | 'ucs2' | 'latin1' | 'binary';

// ...
}

If you plan to use some plain JavaScript code for testing, but you don’t want to invest the time to write type definitions for it, you can use a shorthand ambient module declaration:

buffer.d.ts
1
declare module 'buffer';

¹ 83,086,518 weekly downloads from 2022-12-06 to 2022-12-12