Sub topic 10
Ambient declarations for untyped packages and asset imports
This chapter assumes you can write tsconfig.json, know the difference between a module file and a global script file, and understand how TypeScript resolves an import to a file. You should also have used npm install and read package.json. Here you will learn how to give types to code that has none: untyped npm packages and non-code files such as images that a bundler handles.
The problem: an import with no types
Suppose you install a JavaScript package that ships no types and has no @types package. With strict on, importing it fails:
import { greet } from "legacy-lib";
// error TS7016: Could not find a declaration file for module 'legacy-lib'.
// 'node_modules/legacy-lib/index.js' implicitly has an 'any' type.TypeScript found the JavaScript file but has no type information for it. Under noImplicitAny (part of strict) this is an error. Importing a file that does not exist at all is a different error, TS2307 ("Cannot find module"). Importing an asset such as logo.svg produces TS2307 too, because TypeScript only resolves .ts, .tsx, .d.ts, and .js-family files.
An ambient declaration solves both cases. It tells the compiler "a module with this name exists, and here is its shape" without supplying any implementation.
What "ambient" means
A declaration is ambient when it describes something that exists at runtime but is defined outside the TypeScript code being compiled. The keyword declare marks it. Ambient declarations produce no JavaScript output. They only feed the type checker.
You have seen ambient declarations already: the built-in lib.d.ts files declare Array, Promise, and console this way. declare module "name" { ... } applies the same idea to a module specifier.
Declaring a module by name
Place the declaration in a .d.ts file that is part of your compilation:
// legacy-lib.d.ts
declare module "legacy-lib" {
export function greet(name: string): string;
}Now import { greet } from "legacy-lib" type-checks, and greet("Ada") is checked against the signature. Inside the block you write declarations only, with no function bodies and no initializers (except for literal-valued const).
There is one critical rule: the file must not contain a top-level import or export. A top-level import or export turns the file into a module, and then declare module "legacy-lib" is treated as an augmentation of an existing module instead of a fresh ambient declaration. TypeScript will report that it cannot find the module you are trying to augment. If you need to import a type inside the declaration, put the import inside the declare module block:
// legacy-http.d.ts
declare module "legacy-http" {
import type { IncomingMessage } from "node:http";
export function handle(req: IncomingMessage): Promise<void>;
}Making sure the compiler sees the file
A .d.ts file only helps if it is in the program. Three common ways:
- Keep it under a directory listed in
include. With"include": ["src"], a file atsrc/types/legacy-lib.d.tsis picked up. - List it in
files. - Add a triple-slash reference such as
/// <reference path="./legacy-lib.d.ts" />in a file that is already in the program. Prefer the first two.
A frequent mistake is putting declarations in a folder outside include. The editor may still find them, because it can use a different project, but tsc fails. Run tsc --listFiles to confirm that your declaration file is loaded.
The shorthand ambient module
If you only need the build to pass and do not yet want to write types, declare the module with no body:
// shims.d.ts
declare module "legacy-lib";Every import from legacy-lib now has type any. This is a quick way to unblock work, and it fits a package you use in one place. It costs you all checking on that package, and mistakes such as calling a function that does not exist will not be reported. Treat it as a temporary step and replace it with real declarations when you can.
Wildcard declarations for assets
Bundlers such as webpack, Vite, and esbuild let you import non-code files. The bundler turns import logo from "./logo.svg" into a URL string or a processed asset. TypeScript does not know this, so you declare the shape with a pattern that contains one *:
// assets.d.ts
declare module "*.svg" {
const url: string;
export default url;
}Then this compiles:
import logo from "./logo.svg";
const img = document.createElement("img");
img.src = logo;You can add one declaration per extension. Different bundler setups give different values, so match what your bundler actually produces:
// assets.d.ts
declare module "*.png" {
const url: string;
export default url;
}
declare module "*.module.css" {
const classes: { readonly [className: string]: string };
export default classes;
}The CSS modules declaration gives a lookup object from class name to generated class name. Using readonly stops accidental writes.
Two details matter here:
- The pattern is matched against the specifier text exactly as written in the import.
"*.svg"matches"./logo.svg"and"../icons/a.svg". It also matches"logo.svg". - The default export is a design choice. If your bundler exposes a named export as well, such as a React component for SVG files, declare it too. Types that disagree with the bundler cause runtime failures that the compiler cannot catch.
Many frameworks ship these declarations for you. Vite provides vite/client, which you enable with "types": ["vite/client"] in compilerOptions, or with a triple-slash /// <reference types="vite/client" /> line. Check your framework before writing your own, so that you do not declare the same module twice with conflicting shapes.
Declaring a global variable
Ambient declarations also describe values that a script tag or the host environment places in the global scope:
// globals.d.ts
declare const APP_VERSION: string;
interface Window {
analytics?: { track(event: string): void };
}This file has no top-level import or export, so it is a global script and the declarations are global. APP_VERSION could be replaced by a bundler's define option at build time. The Window interface merges with the built-in one through declaration merging, which adds an optional property.
If such a file does need an import, make it a module and use declare global { ... } for the global part. The next chapters cover that form together with module augmentation.
Choosing between approaches
| Situation | Approach | Trade-off |
|---|---|---|
| Package has no types, used once | `declare module "name";` | Everything is `any` |
| Package used widely, small API | Full `declare module "name" { ... }` | You must keep it in sync |
| Package has a community typing | Install `@types/name` | Version may lag the package |
| Bundler-handled file type | `declare module "*.ext"` | Must match bundler behavior |
| Host-provided global | `declare const` or `declare function` | Not checked at runtime |
If the package is popular, search for @types/<name> first. Installing it is better than hand-written declarations, because someone maintains it.
Common errors
- TS7016 persists after adding a declaration. The file is not in the program, or it has a top-level
importorexportthat turned it into a module. Checkincludeand remove the top-level statement or move it inside the block. - TS2307 for a relative import of a
.tsfile. A wildcard declaration does not help. Check the path and the.jsextension rules for yourmoduleResolutionmode. - Types accepted but runtime
undefined. Your declaration says a function exists that the package does not export. Compare it with the package's actual exports. - Duplicate declarations disagree. Two
declare module "*.svg"blocks with different default export types are reported as conflicts. Keep one. skipLibCheckhides problems. The option skips type checking of all.d.tsfiles, including yours. It speeds up builds but can hide mistakes in declarations you wrote.
A complete small example
Project layout:
{
"compilerOptions": {
"target": "es2022",
"module": "esnext",
"moduleResolution": "bundler",
"strict": true,
"noEmit": true
},
"include": ["src"]
}// src/types/legacy-lib.d.ts
declare module "legacy-lib" {
export function greet(name: string): string;
}
// src/types/assets.d.ts
declare module "*.svg" {
const url: string;
export default url;
}// src/main.ts
import { greet } from "legacy-lib";
import logo from "./logo.svg";
const message: string = greet("Ada");
console.log(message, logo.toUpperCase());Both imports type-check. If you change greet("Ada") to greet(42), the compiler reports that a number is not assignable to a string, which shows that the real declaration is doing its job and not falling back to any.
Exercise
A teammate adds src/types/legacy-lib.d.ts containing import type { Buffer } from "node:buffer"; at the top, followed by declare module "legacy-lib" { export function read(): Buffer; }. The build still reports TS7016 for legacy-lib. Why, and how do you fix it?
Show answer
The top-level import type makes the file a module, so declare module "legacy-lib" is treated as an augmentation of an existing module instead of an ambient declaration of a new one. Move the import inside the declare module "legacy-lib" { ... } block, so the file stays a global script and the declaration defines the module.
Exercise
You import ./theme.module.css and get TS2307. Write the declaration that fixes it, so that styles.header has type string, and explain what it does not guarantee at runtime.
Show answer
Add declare module "*.module.css" { const classes: { readonly [className: string]: string }; export default classes; } to a .d.ts file in the program. It only describes what the bundler is expected to return. It does not check that a class named header exists, and it does not make plain tsc or Node.js able to load CSS files.