Sub topic 10
Declaration merging and when it helps
This chapter assumes you can write interfaces and type aliases, understand structural typing, and can run tsc or read editor errors. Declaration merging is one of the few places where an interface can do something a type alias cannot.
What declaration merging is
When TypeScript finds two or more interface declarations with the same name in the same scope, it combines them into one interface. The merged interface has every member from every declaration.
interface Config {
host: string;
}
interface Config {
port: number;
}
const config: Config = { host: "localhost", port: 8080 };Config now requires both host and port. Leaving either out is an error. The order of the declarations does not change which members exist, but it can matter for overloads, covered below.
A type alias does not merge. Declaring the same alias name twice is an error.
type Settings = { host: string };
// type Settings = { port: number }; // error: Duplicate identifier 'Settings'.This is a real difference between the two constructs. An alias is a single definition. An interface is an open declaration that other code can add to.
Rules for merging members
Merging is simple for most members and has a few restrictions.
Non-function members
Non-function properties with the same name must have identical types. If they differ, the compiler reports an error.
interface Box {
width: number;
}
interface Box {
width: number; // fine: same type
height: number;
}
// interface Box {
// width: string; // error: Subsequent property declarations must have the same type.
// }Repeating a property with the same type is allowed. Giving it a different type is not.
Function members and overloads
Methods with the same name become overloads. Each declaration adds an overload signature to the merged method.
interface Parser {
parse(input: string): number;
}
interface Parser {
parse(input: string[]): number[];
}
declare const parser: Parser;
const a = parser.parse("42"); // number
const b = parser.parse(["1", "2"]); // number[]The order of overloads follows these rules:
- Later interface declarations have their overloads placed before earlier ones.
- Within a single declaration, the original order is kept.
- A signature whose parameter is a single string literal type is moved to the top, whatever its position.
Overload order matters because TypeScript picks the first signature that matches a call. If a general signature such as (input: string) came first, it would hide a more specific literal signature. Rule 3 exists to prevent that.
interface Listener {
on(event: string, handler: () => void): void;
}
interface Listener {
on(event: "close", handler: (code: number) => void): void;
}
declare const listener: Listener;
listener.on("close", (code) => console.log(code.toFixed())); // code is number
listener.on("other", () => {}); // uses the general signatureThe "close" overload comes first in the merged result, so code is typed as number.
Properties versus methods
A property declared with a function type, such as parse: (input: string) => number, is a property and not a method. Two declarations of the same property name with function types conflict instead of becoming overloads. If you want overloads through merging, use method syntax.
Merging across files with global augmentation
Merging is open-ended: the declarations can live in different files. This is the main practical reason the feature exists. A library can define an interface, and your code can add to it.
A common case is adding properties to the global Window interface, which the DOM type definitions declare.
// globals.d.ts
interface Window {
appVersion: string;
}// main.ts
window.appVersion = "1.4.0";
console.log(window.appVersion);This works when globals.d.ts is a script file, meaning it has no top-level import or export. If a file has an import or export, it is a module, and its declarations are local to it. To augment a global from inside a module, wrap the declaration in declare global.
// augment.ts
export {};
declare global {
interface Window {
appVersion: string;
}
}The export {} line makes the file a module. declare global then reaches out and merges into the global Window.
Augmenting a library's types
You can also extend an interface that a package exports. You do this with module augmentation: declare the module by name and reopen the interface inside it.
Express is a typical example. Middleware often attaches data to the request, and the library cannot know your fields in advance.
// express-augment.d.ts
import "express";
declare module "express-serve-static-core" {
interface Request {
userId?: string;
}
}The top-level import makes the file a module, so declare module augments the existing module instead of replacing it. After this, req.userId is known in every handler. Make the property optional when it is only set by some middleware, because TypeScript cannot check that the middleware actually ran.
The module name must match the one that declares the interface. In this case that is express-serve-static-core, not express. Check where the interface is defined in the library's .d.ts files before augmenting it.
Do not rely on a diagram here; the flow is best shown as a sequence.
What cannot merge
Merging has limits, and they explain several confusing errors.
| Situation | Result |
|---|---|
| Interface and interface, same name | Merge |
| Interface and class, same name | Merge (the class instance type gains the interface members) |
| Interface and namespace, same name | Merge |
| Type alias and type alias, same name | Error |
| Type alias and interface, same name | Error |
The interface-and-class case is useful and also risky. The interface members are added to the class's instance type, but the compiler does not check that the class implements them.
interface Animal {
speak(): string;
}
class Animal {
name = "unnamed";
}
const a = new Animal();
// a.speak() type-checks, but no implementation exists at runtime.
// a.speak(); // TypeError: a.speak is not a functionThe compiler accepts the call because the merged type says speak exists. The runtime fails. Avoid this pattern unless something else, such as a mixin helper, really installs the members.
When merging helps
Merging is a good fit in a small set of situations.
- Extending types you do not own. Adding fields to
Window,Request,process.envtypings, or a plugin's options interface. - Plugin architectures. A core library declares an empty interface, and each plugin adds its own entry. The merged interface then describes everything installed.
- Polyfills and runtime additions. If your environment adds a method to a built-in such as
Array, you can declare it on the matching interface.
The plugin pattern looks like this.
interface EventMap {}
interface EventMap {
login: { userId: string };
}
interface EventMap {
logout: { reason: string };
}
function emit<K extends keyof EventMap>(name: K, payload: EventMap[K]): void {
console.log(name, payload);
}
emit("login", { userId: "u1" });
emit("logout", { reason: "timeout" });
// emit("login", { reason: "x" }); // error: wrong payload for "login"In real code the three declarations would be in different files. Each feature adds its own event, and emit checks every call against the combined map.
When merging causes surprises
Merging is silent. TypeScript does not warn when two declarations combine, so accidents are easy.
- Name collisions. Two unrelated files in the same global scope that both declare
interface Itembecome one type. A script file (no import or export) shares the global scope with all other script files. Fields from both appear, and objects that matched oneItemmay now fail to compile. - Order-dependent overloads. Because later declarations come first, moving code between files can change which overload a call picks.
- Spreading definitions. The full shape of a type is no longer in one place. Editors can show the merged result, but a reader of one file cannot see it.
- Conflicting property types. The error appears on whichever declaration the compiler checks second, which may be far from the first.
Two habits reduce the risk. Keep ordinary application types inside modules, so their names are local. Use merging on purpose and leave a comment where you do, naming the other file that contributes members.
If you want a name to be closed, use a type alias. The duplicate-identifier error then protects you from accidental overlap.
Summary of the decision
Use an interface when you want others to be able to extend the type by merging, or when you must augment an existing interface. Use a type alias when the shape should be defined in exactly one place. The next chapters build on this when comparing the two constructs as a whole.
Exercise
A file types.ts starts with import { Role } from "./role"; and then contains interface Window { currentRole: Role }. Code elsewhere in the project still reports that window.currentRole does not exist. What is wrong, and how do you fix it?
Show answer
The import makes types.ts a module, so its Window interface is a new local interface and does not merge with the global Window. Wrap the declaration in declare global { interface Window { currentRole: Role } } (keeping the import), so the declaration merges into the global interface.
Exercise
Two files in the same script scope declare interface Options { debug: boolean } and interface Options { debug: string }. What does the compiler do, and what would happen if both were type aliases named Options?
Show answer
With interfaces, the compiler reports an error that subsequent property declarations must have the same type, because merged properties with the same name need identical types. With type aliases, it reports a duplicate identifier error, because aliases never merge.