Declaration Merging
What
Declaration merging is a unique feature of interfaces where the TypeScript compiler automatically combines multiple declarations of the same interface name into a single definition.
How
Simply define the same interface name multiple times. All properties from all declarations will be merged:
interface Spaceship { name: string; }
interface Spaceship { engines: number; }
// The resulting Spaceship type has both 'name' and 'engines'
const ship: Spaceship = { name: "Explorer", engines: 4 };
Why
Merging is primarily useful for extending global types or third-party library definitions. For example, if you want to add a custom property to the browser’s Window object, you can declare an interface named Window in your project. However, for internal application logic, this can often be confusing, which is why type is often preferred as it forbids redeclaration.
Summary
While powerful for environment extensions, use declaration merging with caution to avoid creating non-obvious and hidden type dependencies.