In TypeScript, "declaration merging" is a process through which multiple declarations with the same name are combined into a single one. This allows you to augment existing types with new properties, merge module declarations, or even extend interfaces without explicitly extending them.
To demonstrate declaration merging, let’s look at some examples:
1. Merging Interfaces:
When you have two or more interfaces with the same name, TypeScript automatically merges their properties into one interface.
interface Box {
height: number;
width: number;
}
interface Box {
scale: number;
}
let newBox: Box = {
height: 10,
width: 10,
scale: 2
};
Above, the two interfaces with the name ‘Box‘ are merged, and the ‘newBox‘ object can now use properties from both.
2. Merging Namespaces:
You can also merge namespaces with the same name. When you do this, the exported members of each namespace are combined.
namespace Animals {
export class Dog {
bark() {
console.log("Woof!");
}
}
}
namespace Animals {
export class Cat {
meow() {
console.log("Meow!");
}
}
}
let myDog = new Animals.Dog();
let myCat = new Animals.Cat();
In the example above, the two ‘Animals‘ namespaces are merged, allowing you to use the ‘Dog‘ and ‘Cat‘ classes under the ‘Animals‘ namespace.
3. Merging Interfaces and Namespaces:
It is also possible to merge an interface declaration with a namespace declaration that has the same name.
interface Greeting {
message: string;
}
namespace Greeting {
export function sayHello() {
console.log('Hello');
}
}
// Usage
let greeting: Greeting = {message: 'Hi there'};
Greeting.sayHello();
In this example, an interface ‘Greeting‘ is merged with a namespace ‘Greeting‘. The result is a single ‘Greeting‘ that has the property ‘message‘ from the interface and the ‘sayHello‘ function from the namespace.
Merging declarations simplify and extend existing types or modules by combining their properties or members. However, it is essential to use this feature judiciously, since overusing it could lead to confusion and make code harder to maintain.