TypeScript Declaration Merging
Declaration merging is a TypeScript feature where multiple declarations with the same name are automatically combined into a single definition. It works most notably with interfaces.
This feature is especially useful for extending existing types, such as adding custom properties to a global object or to types from a third-party library, without modifying its original source code.
interface Config {
a: string;
}
interface Config {
b: number;
}Merging interfaces
If you declare `interface Config { a: string }` and later declare `interface Config { b: number }` in the same scope, TypeScript merges them into one interface requiring both a and b.
Practical use case
Declaration merging is commonly used to add custom properties to global types, such as extending Express's Request type in a Node.js project to include custom fields.
interface Config {
a: string;
}
interface Config {
b: number;
}
const c: Config = { a: "hi", b: 5 };
console.log(c);{ a: 'hi', b: 5 }The two separate Config declarations are merged, so the final type requires both a and b.
interface Window {
myGlobalFlag: boolean;
}
// Elsewhere in the app, code can now safely use window.myGlobalFlag
const flagExists: boolean = true;
console.log(flagExists);trueMerging a custom property into the global Window interface lets you safely add new global properties.
Key points
- Declaration merging combines multiple same-named declarations into one.
- It works with interfaces, but not with type aliases or classes in the same way.
- It's commonly used to extend third-party or global types.
- Merged interfaces require all combined properties together.
