2015-07-20 76 views
1

創建新的Typescript數據類型我想通過擴展現有的Array來創建新的數據類型。通過擴展現有的

這裏是一個擴展的例子:

interface Array<T> { 
    Count(): number; 
} 

Array.prototype.Count = function() { 
    return this.length; 
} 

令我擔心的是與現有的數據類型搞亂。有沒有辦法用新的數據類型創建一個新的數據類型的擴展名爲Array

例如,我們稱之爲List<T>。其中ListArrayCount()方法。

我已經看過Class List<T> extends Array<T>但這不起作用。有什麼建議麼?

更新2016-04

有了新的更新,以打字稿,我給它一個鏡頭...

當前實現:

class List<T> extends Array<T> { 
    private _items: Array<T> = []; 
    constructor(items: Array<T>) { 
     super(); 
     this._items = items; 
    } 
    public where(filter: any, ...arg): Array<T> { 
     return this._items.filter(item => filter(item, ...arg)); 
    } 
} 

以下工作:

interface IItem { 
     name: string 
    } 

    let items = Array<IItem> = []; 

    // add few 'item's to items.  

    let list = new List<IItem>(items); 
    let filter = (item: IItem, name: string) => { return item.name === name }; 
    let filteredList = list.where(filter, name); 

想得到這個工作G:

let list = List<IItem> = []; 

// add few 'item's to items.  

let filter = (item: IItem, name: string) => { return item.name === name }; 
let filteredList = list.where(filter, name); 

編譯器錯誤:

[ts] Type 'undefined[]' is not assignable to type 'List<IItem>'. 
Property '_items' is missing in type 'undefined[]'. 

我這麼想嗎?

+0

@索尼,有什麼建議嗎?見上面更新的部分。 –

回答

0

子分類內置類型隨ES2015(又名ES6/Harmony)而來,但沒有瀏覽器現在默認啓用此功能(請參閱compatibility table)。

你唯一正確的選項現在是使用一些原型黑客...

2

你可能的方式,現在是一個有點哈克做到這一點,但是,可以讓你輕鬆地更換執行子類時,本機類型到達。

的設置看起來像這樣...

interface IList<T> extends Array<T> { 
    count(): number; 
} 


var ListShim = function() { 
    this.count =() => { 
     return this.length; 
    } 
} 
ListShim.prototype = new Array(); 

class List<T> { 
    static create<T>() : IList<T> { 
     return <IList<T>> new ListShim(); 
    } 
} 

並且你使用這樣的:後來

var list = List.create<string>(); 

list.push('test a'); 
console.log(list.count()); 
console.log(list[0]); 

list.push('test b'); 
console.log(list.count()); 
console.log(list[1]); 

,如果你發現你可以子類中的原生型(即所有的瀏覽器都允許它),您可以在不更改調用代碼的情況下替換實現。

interface IList<T> extends Array<T> { 
    count(): number; 
} 

class List<T> extends Array<T> { 
    static create<T>() : IList<T> { 
     return new List(); 
    } 

    count() { 
     return this.length; 
    } 
} 

這最後一個代碼塊是「在黑暗中刺」,因爲我不知道這是什麼會真正的樣子,但你應該從具體的細節你create工廠方法絕緣。

+0

太棒了!像夢一樣工作...一個愚蠢的問題:爲什麼不能用'var ListShim =()=>來替換var ListShim = function()...''@Steve –

+1

@FlippieCoetser因爲那麼它會使用在函數外部找到的'this'的值 - 'this'不等於實例。 –