TypeScript ยท Chapter 39 of 44

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.

Syntax
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.

Example 1 (typescript)
interface Config {
  a: string;
}
interface Config {
  b: number;
}
const c: Config = { a: "hi", b: 5 };
console.log(c);
Output
{ a: 'hi', b: 5 }

The two separate Config declarations are merged, so the final type requires both a and b.

Example 2 (typescript)
interface Window {
  myGlobalFlag: boolean;
}
// Elsewhere in the app, code can now safely use window.myGlobalFlag
const flagExists: boolean = true;
console.log(flagExists);
Output
true

Merging 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.
๐Ÿ’ก Note: Declaration merging is powerful but can be confusing if overused; use it mainly for legitimate type extension needs.

๐Ÿ“ Quick Quiz

1. What does declaration merging combine?

2. Which TypeScript feature commonly uses declaration merging?

3. What is a common practical use of declaration merging?