I'm reading a bit about declaration merging in TypeScript and I have a hard time grokking the use case for it, specifically for interfaces.
In their documentation, they have this example:
That is, in the example:
interface Cloner { clone(animal: Animal): Animal; } interface Cloner { clone(animal: Sheep): Sheep; } interface Cloner { clone(animal: Dog): Dog; clone(animal: Cat): Cat; }
The three interfaces will merge to create a single declaration as so:
interface Cloner { clone(animal: Dog): Dog; clone(animal: Cat): Cat; clone(animal: Sheep): Sheep; clone(animal: Animal): Animal; }
Why would one want to create three separate interfaces instead of the resulting declaration?
For example, you might want to add a method to the window object, so you'll do this:
interface Window {
myMethod(): string;
}
window.myMethod = function() {
...
}
This is very useful when you need to polyfill:
interface String {
trimLeft(): string;
trimRight(): string;
}
if (!String.prototype.trimLeft) {
String.prototype.trimLeft = function() { ... }
}
if (!String.prototype.trimRight) {
String.prototype.trimRight = function() { ... }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With