2017-07-08 57 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; 
}