Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use case for declaration merging?

Tags:

typescript

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?

like image 748
ahstro Avatar asked Sep 13 '25 16:09

ahstro


1 Answers

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() { ... }
}
like image 174
Nitzan Tomer Avatar answered Sep 16 '25 23:09

Nitzan Tomer