2017-07-03 78 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」 –