2017-07-08 65 views
1

我正在尋找在TypeScript中創建數組擴展「排序」方法,其中數組可以由各種對象類型組成。我可以從任何組件調用這個擴展方法。TypeScript - 數組排序擴展方法

這種排序需要在一個對象屬性中進行排序(屬性可以是數字或字符串當然)和方向是枚舉類型(升序1或降序-1)。我有數組,我有sortDirection的枚舉。但是,我在哪裏/如何構建排序方法來像這樣調用它?

myArrayOfObjects.sort('name', sortDirection.Descending); 

這裏是我現有的組件級排序,我試圖把它變成一個可以從任何地方調用的擴展方法。這是很容易把方向變成一個枚舉,並通過它,但我真的想使這是一個擴展方法:

sort(property: string): void { 
    this.isDescending = !this.isDescending; 
    this.column = property; 
    const direction = this.isDescending ? 1 : -1; 

    this.searchResults.sort(function (a, b) { 
     if (a[property] < b[property]) { 
      return -1 * direction; 
     } else if (a[property] > b[property]) { 
      return 1 * direction; 
     } else { 
      return 0; 
     } 
    }); 
    this.currentPage = 0; 
} 

this.searchResults低於,但它可以是任何數組或任何物體與屬性。再次,這是目前的分量級函數,我想變成擴展方法用於數組:

@Input() searchResults: IPersonSummary[]; 
+0

[在打字稿擴展陣列]的可能的複製(https://stackoverflow.com/questions/12802383/extending-array-in-typescript) – toskv

回答

2

由於打字原稿裝入其中的定義方法與名稱排序鹼分型不能與重新定義它一樣的名字。如果你考慮使用一些不同的名字(例如我選擇mySort),你可以這樣做。你需要在Array接口中定義它,並將你的函數分配給Array原型。 使用新名稱定義擴展是最佳實踐,因爲您無法隨時調用基本方法,因爲您重寫了一些基本方法。如果你考慮在將來某個時候調用基本方法,你將會遇到很大的麻煩。

推薦的方式來做到這一點:

interface Array<T> { 
    mySort(property: string): void; 
} 

Array.prototype.mySort = function (property: string): void { 
    this.isDescending = !this.isDescending; 
    this.column = property; 
    const direction = this.isDescending ? 1 : -1; 

    this.searchResults.sort(function (a, b) { 
     if (a[property] < b[property]) { 
      return -1 * direction; 
     } else if (a[property] > b[property]) { 
      return 1 * direction; 
     } else { 
      return 0; 
     } 
    }); 
    this.currentPage = 0; 
}