Lesson 46 of 50TypeScript
Declaration Files and Module Augmentation
Write .d.ts files, type untyped packages, add fields to Window, process.env and library types, and publish a package whose types actually resolve.
Three tickets you will see in your first months: "add user.id to the session type so we stop casting", "the analytics script puts dataLayer on window and TypeScript does not know about it", and "this old PDF package has no types". None of them is solved by writing ordinary code. Each one needs a declaration: a statement to the compiler about something that exists at runtime but is not written in TypeScript. This lesson covers how .d.ts files work, how to extend types you do not own, and how library authors ship types that work for everyone. Modules and tsconfig introduced .d.ts files and DefinitelyTyped; here you go a level deeper.
What a declaration file is
A .d.ts file holds only types. The compiler reads it, and nothing in it ever runs. Every line starts with declare, export, interface, type or import, and no function has a body.
export interface SlugOptions {
separator?: string;
lower?: boolean;
}
export declare function slugify(input: string, options?: SlugOptions): string;
export declare const VERSION: string;declare means "this exists, trust me, here is its type". It is a promise with no check behind it. If the JavaScript does not match, you find out at runtime. That is the whole risk of declaration files, and why you keep them small and close to the code they describe.
Script or module: the rule that breaks everything
The most important rule about .d.ts files is easy to miss. A file with no top-level import or export is a script: everything it declares is global. A file with at least one top-level import or export is a module: its declarations are private unless exported.
This flips the meaning of declare module "x":
- In a script,
declare module "legacy-pdf" { ... }creates a new module. This is how you type an untyped package. - In a module, the same text augments an existing module. If
legacy-pdfhas no types already, there is nothing to augment, and imports of it fail.
So when someone adds import type { Foo } from "./foo" to the top of types/legacy.d.ts, the file silently becomes a module, and every import of legacy-pdf breaks with "Cannot find module". The fix is to move the import inside the declare module block, or use an inline import("./foo").Foo type.
Typing an untyped package
When a package has no types, import { render } from "legacy-pdf" fails under strict. Work through these in order.
- Search for
@types/legacy-pdf. If it exists, install it as a dev dependency. Done. - Check if a newer version of the package ships its own types.
- Write a declaration for only what you use.
declare module "legacy-pdf" {
export interface PdfOptions {
pageSize?: "A4" | "Letter";
margin?: number;
}
export function render(html: string, options?: PdfOptions): Promise<Uint8Array>;
}Three functions you call, typed carefully, beat a 400-line attempt to type the whole library. If you are in a hurry, the shorthand declare module "legacy-pdf"; makes every import from it any. That unblocks the build but turns off checking for that package, so treat it as a temporary ticket, not a fix.
For a CommonJS package that sets module.exports = function () {}, the declaration uses export =:
declare module "old-cjs-lib" {
function create(name: string): { start(): void };
export = create;
}If your declarations are good and the package is popular, contribute them to DefinitelyTyped. The repository has one folder per package under types/, each with an index.d.ts, a test file that uses the types, and a package.json. A pull request is reviewed by the package's listed owners, and once merged it publishes as @types/<name> automatically. It is a well-regarded first open-source contribution, and an easy thing to point to in an interview.
Global augmentation: Window and process.env
Some values are globals that your code did not create: a third-party script tag on window, or environment variables. You add them with declare global inside a module file:
declare global {
interface Window {
dataLayer: unknown[];
}
namespace NodeJS {
interface ProcessEnv {
DATABASE_URL: string;
NODE_ENV: "development" | "production" | "test";
}
}
}
export {};The export {} at the end is not decoration. It makes the file a module, and declare global is only allowed in modules. Remove it and you get an error saying augmentations for the global scope can only be nested in external modules.
Be honest about what this does. The ProcessEnv addition says DATABASE_URL is always a string. Nothing checks that. If the variable is missing in production, the code compiles and then fails with undefined. A declaration like this is fine only if something validates the environment at startup; End-to-End Type Safety shows that pattern. For window, prefer optional fields (dataLayer?: unknown[]) when the script might be blocked by an ad blocker.
Bundler globals: import.meta.env and asset imports
Vite exposes env variables on import.meta.env, not process.env, and types them through an interface you extend in src/vite-env.d.ts:
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_API_URL: string;
readonly VITE_SENTRY_DSN?: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}This file has no imports, so it is a script, and both interfaces merge into the global ones that vite/client declares. The triple-slash reference line pulls in Vite's own declarations, which also include wildcard modules for *.svg, *.png and *.module.css. That is why a fresh Vite app can import images without you writing declare module "*.svg". If you delete the reference line to "clean up", every asset import breaks. Next.js does the same job with its generated next-env.d.ts, which it rewrites on every dev and build, so you never edit it by hand.
Declaration merging
declare global works because of declaration merging: when two interface declarations share a name in the same scope, TypeScript combines them into one.
interface Settings {
theme: "light" | "dark";
}
interface Settings {
language: string;
}
const s: Settings = { theme: "dark", language: "en" }; // both fields requiredWindow is an interface in the DOM library, so your interface Window { dataLayer } merges into it. A type alias does not merge. Writing type Settings = ... twice is a "Duplicate identifier" error. This is the one real behavioural difference between interface and type that you saw in Interfaces and Type Aliases, and it is why library authors expose interfaces for anything they expect you to extend.
A few merging details seniors know:
- If both declarations have the same property with different types, it is an error. Merging adds; it cannot change.
- Merged methods with the same name become overloads, and the later declaration's overloads are listed first.
- A
classand aninterfacewith the same name merge too, which lets you add declared fields to a class from outside.
Press Run (⌘ Enter) to see what happens.Module augmentation of libraries
The same merging lets you extend a library's types from your code. You write declare module "<package>" in a module file and reopen one of its interfaces. The Auth.js session is the classic case:
import type { DefaultSession } from "next-auth";
declare module "next-auth" {
interface Session {
user: {
id: string;
role: "admin" | "member";
} & DefaultSession["user"];
}
}Now session.user.id is typed everywhere, with no casts. You must still put id on the session in the auth callbacks; the declaration only describes what your callback returns.
Express attaches the logged-in user to the request in middleware. @types/express declares a global Express namespace for exactly this:
declare global {
namespace Express {
interface Request {
user?: { id: string; role: "admin" | "member" };
}
}
}
export {};Some libraries design for this on purpose. TanStack Router asks you to register your router so every Link knows the real routes:
declare module "@tanstack/react-router" {
interface Register {
router: typeof router;
}
}The library has an empty Register interface and reads Register["router"] in its own types. You fill it in, and the whole API becomes specific to your app. This registry pattern shows up in i18n libraries, form libraries and test matchers too.
When an augmentation "does nothing", check these, in order:
- The file is a module (has an
importorexport). - The file is in the program: covered by
includeintsconfig.json. - The module name matches what the library declares. Express's
Requestactually lives inexpress-serve-static-core, which is why the global namespace route is easier. - You are augmenting an interface. A
typealias cannot be reopened. skipLibCheckis on. It skips checking all.d.tsfiles, including yours, so a typo in your declaration produces no error at all.
export type Theme = { primary: string } and you want to add your own colours. You write declare module "ui-lib" { type Theme = { accent: string } } in a module file. What happens?The library ships an interface Session with a generic user. Because it is an interface, it can be reopened.
src/types/legacy-pdf.d.ts has worked for a year. A teammate adds import type { Margin } from "../lib/units"; at the top, and now every import { render } from "legacy-pdf" fails with Cannot find module. Why?JSDoc types and checkJs
Not every codebase is TypeScript. Many teams type-check plain JavaScript with JSDoc comments, either to migrate slowly or to keep a build-free codebase. Turn on allowJs and checkJs in tsconfig.json, or add // @ts-check to one file.
// @ts-check
/** @import { Product } from "./types" */
/**
* @typedef {{ product: Product; qty: number }} CartLine
*/
/**
* @param {CartLine[]} lines
* @param {number} [discountPercent]
* @returns {number}
*/
export function total(lines, discountPercent = 0) {
const sum = lines.reduce((acc, l) => acc + l.product.priceCents * l.qty, 0);
return Math.round(sum * (1 - discountPercent / 100));
}The checker treats these comments as real types, so you get the same errors and editor help. The @import tag (TypeScript 5.5) imports types from .ts or .d.ts files without a runtime import. With declaration on, tsc can even emit .d.ts files from JSDoc, which is how some well-known libraries ship types while staying in JavaScript.
Match each goal to the declaration that achieves it.
Publishing types that resolve
When you build a package, its types have to be found by every consumer setup: bundler and nodenext resolution, ESM and CommonJS. The modern way is the exports field, with a types condition listed first in each branch, because conditions match top to bottom.
{
"name": "@acme/money",
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"files": ["dist"]
}Dual packages (ESM and CommonJS builds side by side) are where most type bugs live. Each format needs its own declaration file, .d.mts next to the ESM build and .d.cts next to the CommonJS one, because the declaration's extension tells TypeScript which module format the JavaScript is. Point both conditions at one index.d.ts and the types masquerade: TypeScript thinks CommonJS users are importing ESM, or the reverse, and default imports break in ways that only some users see.
Two tools catch this before you publish:
npx @arethetypeswrong/cli --pack .npx publintAre the types wrong? packs your package and resolves it under every resolution mode, reporting problems such as "masquerading as ESM" or "types not found under node16". publint checks package.json fields against what Node and bundlers actually do. Run both in CI for any published package.
Since Node 22.12 can require() an ES module, many libraries now ship ESM only, which removes the dual-package problem completely. For a new internal or public package in 2026, start ESM only unless you know a consumer needs CommonJS.
Put these in the order TypeScript tries them when resolving types for import { x } from "pkg" (with modern resolution).
- Tap the steps below in the right order.
- src/
- types/
- globals.d.tsdeclare global: Window, ProcessEnv. Ends with export {}
- assets.d.tsdeclare module "*.svg", "*.module.css". A script, no imports
- legacy-pdf.d.tsdeclare module "legacy-pdf". A script, no imports
- next-auth.d.tsaugmentation. A module: imports from next-auth
- tsconfig.jsoninclude covers src/types
- declaration file
- A
.d.tsfile that describes the types of code that exists elsewhere. Nothing in it runs. - ambient declaration
- A
declarestatement that tells the compiler something exists at runtime, with no check that it does. - script vs module
- A file with no top-level import or export is a global script. One import or export makes it a module with its own scope.
- declaration merging
- Interfaces (and namespaces) with the same name combine into one. Type aliases do not merge.
- module augmentation
- Reopening an interface from another module with
declare module "pkg"inside a module file. - global augmentation
- Adding to the global scope, such as
Window, withdeclare globalinside a module file. - masquerading types
- A package whose declaration files claim a different module format (ESM or CJS) than its JavaScript actually is.