简体   繁体   English

声明合并的用例是什么?

[英]What is the use case for declaration merging?

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. 我在阅读有关TypeScript中声明合并的内容 ,并且很难理解它的用例,尤其是对于接口。

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: 例如,您可能想向window对象添加一个方法,因此您可以这样做:

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() { ... }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM