2017-07-03 81 views
0

我正在读一些关于TypeScript中的declaration merging的信息,我很难对它的用例进行分析,特别是对于接口。声明合并的用例是什么?

在他们的文件,他们有这样的例子:

也就是说,在这个例子:

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; 
} 

为什么要创建三个单独的接口而不是由此产生的声明?

回答

2

例如,你可能想的方法添加到窗口对象,所以你会做到这一点:

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

所以它只是为了扩展现有的接口,否则,有权访问?会不会有编写自己的重复声明的情况? – ahstro

+1

这是一个用例,但欢迎您扩展自己的类型。例如,假设您有一个定义了接口“MyInterface”的模块,但是您可能会加载另一个模块,该模块在加载时会扩展此“MyInterface” –