繁体   English   中英

声明合并的用例是什么?

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

我在阅读有关TypeScript中声明合并的内容 ,并且很难理解它的用例,尤其是对于接口。

在他们的文档中,他们有以下示例:

也就是说,在示例中:

 interface Cloner { clone(animal: Animal): Animal; } interface Cloner { clone(animal: Sheep): Sheep; } interface Cloner { clone(animal: Dog): Dog; clone(animal: Cat): Cat; } 

这三个接口将合并以创建单个声明,如下所示:

 interface Cloner { clone(animal: Dog): Dog; clone(animal: Cat): Cat; clone(animal: Sheep): Sheep; clone(animal: Animal): Animal; } 

为什么要创建三个单独的接口而不是结果声明?

例如,您可能想向window对象添加一个方法,因此您可以这样做:

interface Window {
    myMethod(): string;
}

window.myMethod = function() {
    ...
}

当您需要填充时,这非常有用:

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