2017-01-15 128 views
3

"Typescript extend String Static"後擴展陣列 ,我得到了,我們可以擴展打字稿的現有基類,例如幾下,加入新的方法 如何在打字稿

interface StringConstructor { 
    isNullOrEmpty(str:string):boolean; 
} 
String.isNullOrEmpty = (str:string) => !str; 

它確實工作。但對於通用接口,我遇到了問題。例如,我需要在Array中添加新的方法contains()。我使用下面的代碼:

//1 
    interface Array<T> { 
     contain(item: T): boolean; 
    } 
    //2 
    ?????? = (item: T) => { 
    // .... 
     return true; 
    }; 

第一步後,在VS智能感知,並彈出包含的方法,但在那裏我可以做的實現方法?

+0

可能重複[擴展數組在TypeScript](http://stackoverflow.com/questions/12802383/extending-array-in-typescript) –

回答

3

正如在接口的定義,已經被綁定到通用約束,在實現你可以把它當作任何:

interface Array<T> { 
    contain(item: T): boolean; 
} 

Array.prototype.contain = function(item) { 
    return this.some(obj => item == obj); 
}; 

另外,不要使用箭頭函數原型方法,這裏的原因:

interface Array<T> { 
    fn(): void; 
} 

Array.prototype.fn =() => { 
    console.log(this); 
}; 

let a = []; 
a.fn(); // Window 

但是:

Array.prototype.fn = function() { 
    console.log(this); 
}; 

let a = []; 
a.fn(); // [] 

如果你的目標es5或更低,那麼它並不重要,因爲編譯器會將箭頭函數轉換爲常規函數,但如果您將切換到定位es6(並且箭頭函數將會持續),那麼您的代碼將會中斷,您將不知道爲什麼。

+0

嗨Nitzan,謝謝你的答案...如果實現它作爲一個實例方法,它應該與.net框架中的相同。我發現是否使用箭頭函數,intellisense提示參數項是什麼,沒有數組本身必須在方法體中使用..有關在方法體中獲取數組的任何建議? – VinceDan

+0

它應該是一個實例方法還是靜態方法?它基於你發佈的簽名是有意義的,它是一種實例方法。該項目是你在數組內尋找什麼?如果是這樣,它應該是'任何' –

+0

我喜歡做實例方法,因爲我是.net開發者.. :-)我關心的是方法體,我無法獲得數組[],我需要數組[ ],並且已經傳入並寫入的項目包含邏輯... – VinceDan