Declaration Merging
Declaration merging is TypeScript's rule that two or more declarations with the same name in the same scope combine into a single type. Interfaces, namespaces, and enums merge; type aliases do not.
Detailed Explanation
Write interface User { id: string } in one place and interface User { email: string } in another, and you do not get a duplicate-name error. You get one User with both members. That is deliberate, and it exists because TypeScript had to describe JavaScript that was never designed to be described.
Consider the browser's Window. It is defined across several library files, and every library that attaches something to it — an analytics snippet, a feature-flag client — adds a property the original authors never knew about. There was no way to edit the original declaration. Merging is the escape hatch: you re-open the interface and add what is actually there.
The merge rules are specific.
- Interfaces combine their members. Two members with the same name must have identical types, or the compiler reports
Subsequent property declarations must have the same type. - Same-named methods become an overload set rather than a conflict. Ordering matters: signatures from the later interface are placed before the earlier ones, so the later declaration wins on ambiguous calls.
- Namespaces merge their exported members. Anything not exported stays private to its own block, so two namespace blocks cannot see each other's internals.
- A namespace can merge with a function, class, or enum of the same name. This is how you attach static properties to a function — the old way of modelling
jQuery.ajaxalongsidejQuery(). - Type aliases never merge. A second alias with the same name is
Duplicate identifier.
Two forms do the real work in modern code. declare global { ... } re-opens a global interface from inside a module — the standard way to type window.dataLayer. And module augmentation, declare module "some-pkg" { ... }, re-opens an interface exported by a dependency. That is how you add req.user to Express or a custom property to a theme object.
Module augmentation has constraints people trip over. The file must itself be a module, meaning it needs at least one top-level import or export. You can only patch declarations that already exist; you cannot introduce new top-level names, and you cannot augment a default export. The file must also be included in the compilation, so if nothing imports it, list it in files or include or the augmentation silently does nothing.
The cost is action at a distance. A type's true shape is no longer visible where it is declared, and "go to definition" lands on whichever fragment you clicked. Merging is also unchecked against reality: declaring that Request has a user property does not make any middleware set it. That is why augmentations should usually declare the property optional, or mark it as set-by-middleware in a comment. Use merging when you genuinely cannot edit the original declaration. When you can, extends is easier to follow.
Code Examples
1. Interfaces merge members; conflicting types are an error.
// 1. Interfaces merge members; conflicting types are an error.
interface Session {
userId: string;
}
interface Session {
expiresAt: Date;
}
const s: Session = { userId: "u_42", expiresAt: new Date() }; // both are required
interface Session {
userId: number;
}
// Error: Subsequent property declarations must have the same type. Property 'userId' must be of type 'string'.2. Augmenting a global interface from inside a module.
// 2. Augmenting a global interface from inside a module.
export {}; // makes this file a module, which 'declare global' requires
declare global {
interface Window {
// Optional, because the snippet that defines it may not have loaded yet.
analytics?: { track(event: string, props?: Record<string, unknown>): void };
}
}
window.analytics?.track("checkout_started", { cartSize: 3 });3. A namespace merging with a function to hold its statics.
// 3. A namespace merging with a function to hold its statics.
function parseConfig(raw: string): Record<string, string> {
const out: Record<string, string> = {};
for (const line of raw.split("\n")) {
const eq = line.indexOf("=");
if (eq > 0) out[line.slice(0, eq)] = line.slice(eq + 1);
}
return out;
}
namespace parseConfig {
// Merged onto the function value itself, so both call styles typecheck.
export const version = "2";
export type Result = Record<string, string>;
}
const cfg: parseConfig.Result = parseConfig("region=ap-south-1");
console.log(parseConfig.version); // "2"Common Gotchas
Type aliases cannot be merged or augmented
if a library exports its options object as `type Options = { ... }`, there is no supported way to add a field to it. Only interfaces, namespaces, classes, and enums participate in merging.
An augmentation that is never imported does nothing
the file has to be part of the program. Nothing errors; your new property is silently absent, which reads exactly like a typo in the interface name.
Merging asserts, it does not verify
adding `user: User` to Express's `Request` makes the compiler trust every `req.user` access even on routes with no auth middleware. Declare it optional and narrow it, or you have traded a type error for a runtime crash.
Method merges reorder your overloads
members from the later interface are inserted ahead of earlier ones. If two signatures could both match a call, the one from the file that loaded last is chosen, which makes resolution depend on declaration order.