TypeScript declaration files, merging and namespaces
A TypeScript program constantly uses code that TypeScript did not compile: the JavaScript runtime, Node.js, npm packages written in JavaScript, and globals injected by a browser or a framework. The compiler learns their types from declarations: type information without implementation, usually in .d.ts files. This hub covers how declarations work, how TypeScript merges several declarations of the same name into one, how you use that to add members to someone else’s module or to the global scope, and where namespaces, TypeScript’s pre-ES-module way of organizing code, still fit.
ES modules (import and export) are the basis for everything here. The Modules and compilation tutorial introduces them, and the JavaScript page on modules covers their runtime behavior.
Samples were compiled with TypeScript 7.0.2 (tsc --strict --target es2025 --module nodenext --types node, with @types/node installed) and run with Node.js 22. Multi-file samples show each file name in a comment on its first line; put the files in one folder next to a package.json containing {"type": "module"} and run npx tsc on the entry file, which pulls in the others.
Topics on this page
Section titled “Topics on this page”| Topic | Since | Use it when |
|---|---|---|
| Declaration files | TypeScript 0.8 | You use JavaScript code or publish a library with types. |
| Declaration merging | TypeScript 0.8 | Several declarations should describe one entity. |
| Module augmentation | TypeScript 1.8 | You add members to a module or global you do not own. |
| Namespaces | 1.5 (as namespace) |
You describe a global library or group types without modules. |
Declaration files
Section titled “Declaration files”Declaration files have been part of TypeScript since its first release. A .d.ts file contains only types: declare statements for functions, classes and variables, plus interfaces and type aliases, with no executable code. The compiler uses them to type-check calls into JavaScript it cannot see.
Declarations come from three places. TypeScript ships the lib files for the JavaScript language and the DOM, selected by the target and lib options. Many npm packages include their own .d.ts files, found through the types or exports fields in their package.json. For JavaScript-only packages, the community DefinitelyTyped project publishes types under the @types scope, such as @types/node. Since TypeScript 6.0, the types compiler option defaults to [], so global declarations from @types packages, such as Node.js’s process, are loaded only when listed: "types": ["node"].
When you compile your own library, the declaration option makes tsc write a .d.ts file next to each .js file, which is what consumers of a published package use. For a small piece of internal JavaScript, writing a .d.ts by hand next to the .js file is enough: a relative import of ./legacy-tax.js finds ./legacy-tax.d.ts.
// legacy-tax.d.ts: types for an existing JavaScript moduleexport interface TaxResult { net: number; vat: number; gross: number;}
export declare const DEFAULT_RATE: number;export declare function addVat(net: number, rate?: number): TaxResult;The JavaScript file it describes, legacy-tax.js:
export const DEFAULT_RATE = 0.21;export function addVat(net, rate = DEFAULT_RATE) { const vat = Math.round(net * rate * 100) / 100; return { net, vat, gross: net + vat };}And a TypeScript file that uses it:
import { addVat, DEFAULT_RATE, type TaxResult } from "./legacy-tax.js";
const result: TaxResult = addVat(59.9);console.log(`rate ${DEFAULT_RATE}: net ${result.net}, vat ${result.vat}, gross ${result.gross.toFixed(2)}`);Output of node checkout.js:
rate 0.21: net 59.9, vat 12.58, gross 72.48Calling addVat("59.90") fails with error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'., even though the implementation is plain JavaScript.
Pitfalls:
- Declarations are trusted, not checked. If
legacy-tax.d.tssaysgross: numberand the JavaScript returns a string, nothing reports it. Keep hand-written declarations small and tested, or convert the file to TypeScript. skipLibCheckhides errors in.d.tsfiles. It speeds up builds, and is common, but conflicting@typesversions then fail only at the point of use.- Missing globals after upgrading to 6.0 or 7.0. Errors like
Cannot find name 'process'usually mean"types": ["node"]is missing.
Declaration merging
Section titled “Declaration merging”Declaration merging has been part of TypeScript since its first release. When the compiler finds several declarations with the same name in the same scope, it combines them into one entity. Two interfaces named OrderEvents become one interface with the members of both; that is why the DOM and Node.js typings can be extended in separate files and libraries.
TypeScript tracks three meanings for each name: value, type and namespace. Declarations merge when their kinds allow it. Interfaces merge with interfaces (later declarations’ overloads come first). A namespace merges with a function, class or enum of the same name, adding static-like members to it. A class and an interface with the same name merge too, which adds the interface’s members to the class type without implementing them. type aliases never merge: declaring one twice is an error.
Merging is powerful but implicit. In application code, prefer one declaration per name; reach for merging when you extend types you do not own (next section) or describe a JavaScript API that is both a function and an object.
// Interface merging: two declarations, one interface.interface OrderEvents { created: { orderId: string };}interface OrderEvents { shipped: { orderId: string; carrier: string };}
// Function and namespace merging: a callable with properties.function formatMoney(amount: number): string { return `${amount.toFixed(formatMoney.decimals)} ${formatMoney.currency}`;}namespace formatMoney { export const currency = "EUR"; export const decimals = 2;}
function emit<K extends keyof OrderEvents>(name: K, payload: OrderEvents[K]): string { return `${name}: ${JSON.stringify(payload)}`;}
console.log(emit("created", { orderId: "ORD-1" }));console.log(emit("shipped", { orderId: "ORD-1", carrier: "ParcelCo" }));console.log(formatMoney(59.9), formatMoney.currency);Output:
created: {"orderId":"ORD-1"}shipped: {"orderId":"ORD-1","carrier":"ParcelCo"}59.90 EUR EURDeclaring type OrderId = string; twice fails with error TS2300: Duplicate identifier 'OrderId'. Merging interfaces with the same property but different types fails with error TS2717: Subsequent property declarations must have the same type. followed by the two conflicting types.
Pitfalls:
- Accidental merges. An
interface Windoworinterface Requestin a global script silently merges with the DOM’s. Keep code in modules, where names are local. - Class and interface merging skips checks. The class does not have to implement the merged members, so they can be
undefinedat run time.
Module augmentation
Section titled “Module augmentation”Module augmentation arrived in TypeScript 1.8. Inside a module, declare module "package-name" { ... } reopens another module’s declarations and merges new members into them, using declaration merging. declare global { ... } does the same for the global scope. This is how a plugin adds a property to a framework’s request object, or how a polyfill adds a method to Array.
Two rules make it work. The file that augments must itself be a module (it has an import or export), otherwise declare module "x" declares a new ambient module instead of augmenting one. And you can only add to existing declarations, such as new interface members or overloads; you cannot add new top-level exports or change existing types. Augmentation affects types only: the code that actually creates the property, such as a middleware that sets requestId, is your responsibility.
import { createServer, type IncomingMessage } from "node:http";
// Augment Node.js's own module: every IncomingMessage now has an optional requestId.declare module "node:http" { interface IncomingMessage { requestId?: string; }}
// Augment the global scope: a helper on all arrays.declare global { interface Array<T> { sumBy(selector: (item: T) => number): number; }}
Array.prototype.sumBy = function <T>(this: T[], selector: (item: T) => number): number { return this.reduce((sum, item) => sum + selector(item), 0);};
function tagRequest(req: IncomingMessage, id: string): string { req.requestId = id; return `request ${req.requestId} ${req.method} ${req.url}`;}
const lines = [{ sku: "SKU-RED-01", total: 20 }, { sku: "SKU-BLU-02", total: 5 }];console.log(lines.sumBy((l) => l.total));
const server = createServer((req, res) => { res.end(tagRequest(req, "req-42"));});server.listen(0, async () => { const address = server.address(); const port = typeof address === "object" && address ? address.port : 0; const response = await fetch(`http://localhost:${port}/orders/ORD-1`); console.log(await response.text()); server.close();});Output:
25request req-42 GET /orders/ORD-1Pitfalls:
- Augmenting from a script. Without any
importorexport, the file is a global script anddeclare module "node:http"declares a separate module, so the augmentation never applies. - Do not extend built-in prototypes in libraries. The sample’s
sumByis fine for an application, but a library that patchesArray.prototypecan collide with future JavaScript methods or other libraries. - The augmenting file must be compiled. An augmentation in a file that
includeor the import graph does not reach is never seen; import it from your entry point or keep it in an includedtypesfolder.
Namespaces
Section titled “Namespaces”TypeScript originally called these internal modules and declared them with the module keyword; TypeScript 1.5 introduced the namespace keyword for them. A namespace is a named object that groups related values and types, compiled to an immediately invoked function that builds the object. It predates ES modules and solved the same problem: avoiding global name collisions in browser scripts.
ES modules are now the standard way to organize code, and the TypeScript handbook recommends them over namespaces for new code. Three developments make namespaces with runtime code a poorer fit still. TypeScript 6.0 made the old module Foo { } syntax a hard deprecation, and TypeScript 7.0 removes it. The erasableSyntaxOnly option (TypeScript 5.8) rejects namespaces that contain runtime code, because Node.js type stripping cannot run them. And bundlers cannot tree-shake a namespace object as well as separate exports.
Namespaces remain useful in two places: in declaration files, to describe global libraries that expose one object (declare namespace), and for type-only grouping, since a namespace that contains only types emits no code and is allowed under erasableSyntaxOnly.
// A type-only namespace: groups related types, emits nothing.namespace OrdersApi { export interface Order { id: string; total: number; } export type ListResponse = { items: Order[]; nextCursor?: string };}
// The ES-module alternative to a namespace with values: plain exports in a module,// or a const object when you want one name.export const Money = { currency: "EUR", format(amount: number): string { return `${amount.toFixed(2)} ${this.currency}`; },} as const;
const page: OrdersApi.ListResponse = { items: [ { id: "ORD-1", total: 40 }, { id: "ORD-2", total: 15.5 }, ],};console.log(page.items.map((o) => `${o.id} ${Money.format(o.total)}`).join("; "));Output:
ORD-1 40.00 EUR; ORD-2 15.50 EURCompiling module Legacy { export const x = 1; } with TypeScript 7.0 fails with error TS1540: A 'namespace' declaration should not be declared using the 'module' keyword. Please use the 'namespace' keyword instead.
Pitfalls:
- Namespaces across files need ordering. Multi-file namespaces relied on
outFileconcatenation or/// <reference>ordering;outFilewas removed in TypeScript 6.0. Convert them to modules. - Do not mix the two. A namespace inside an ES module is just a nested object; importing it gives no tree-shaking and adds indirection.
Choosing between them
Section titled “Choosing between them”- To type an existing JavaScript file, add a
.d.tsfile next to it, or better, convert it to TypeScript. - To type a JavaScript package, install its
@typespackage if it does not ship types, and list global ones intypes. - To add a property to a framework’s or Node.js’s types, use module augmentation in a module file, near the code that sets the property.
- To add a global, use
declare globalin a module, and only in applications. - To organize your own code, use ES modules; use namespaces only for type-only grouping or global-library declarations.
Interview questions
Section titled “Interview questions”What is a .d.ts file, and where do declarations for an npm package come from?
A file that contains only type declarations, no implementation. A package either ships its own (referenced from types or exports in its package.json), or the community publishes them under @types/<name> on DefinitelyTyped. Since TypeScript 6.0, global @types packages must be listed in the types option to be loaded automatically.
Which declarations can merge, and which cannot? Interfaces merge with interfaces; namespaces merge with namespaces, functions, classes and enums; classes merge with interfaces. Type aliases never merge, and two classes or two functions with bodies conflict.
Why does a module augmentation sometimes have no effect?
Most often because the file is not a module: without a top-level import or export, declare module "x" declares a new ambient module instead of augmenting the existing one. Another common cause is that the augmenting file is not part of the compilation at all.
Are namespaces deprecated?
The namespace keyword is not, but the legacy module Foo { } syntax was deprecated in TypeScript 6.0 and removed in 7.0. Namespaces with runtime code are rejected under erasableSyntaxOnly, and the handbook recommends ES modules for organizing new code.
What does skipLibCheck do, and what is the trade-off?
It skips type-checking of all .d.ts files, which speeds up builds and avoids errors from conflicting third-party typings. The trade-off is that real errors in declarations, including your own generated ones, surface only where the types are used, or not at all.
Senior scenario: OrdersPortal’s Express-style API sets req.user in an authentication middleware, and 40 handlers cast (req as any).user. How would you type this properly?
Add a module augmentation for the framework’s request type, declare module "<framework>" { interface Request { user?: AuthenticatedUser } }, in a module file next to the middleware, and include it in the compilation. Remove the casts and handle the optional user with narrowing, or provide a small requireUser(req) helper that throws a 401 error and returns a non-optional user. For handlers that only run after authentication, a typed wrapper (authenticated((req, user) => ...)) avoids the optional property entirely.
Related pages
Section titled “Related pages”- Modules and compilation: ES modules,
import typeandtsconfig.jsonfor beginners. - Tooling and project structure: module resolution,
types,erasableSyntaxOnlyand declaration output. - Core type system: interfaces, the most common merge target.
Official references
Section titled “Official references”- TypeScript Handbook: Declaration Merging
- TypeScript Handbook: Namespaces
- TypeScript Handbook: Introduction to declaration files
- TypeScript 1.8 release notes: augmenting global and module scope
- TypeScript 6.0 release notes: types default, deprecated module keyword for namespaces
- TSConfig reference: types and declaration
- DefinitelyTyped