javascript - TypeScript - 数组排序扩展方法
我希望在 TypeScript 中创建一个数组扩展的“sort”方法,该数组可以由各种对象类型组成。我可以从任何组件调用这个扩展方法。
这种排序需要接受一个对象属性来进行排序(当然该属性可以是数字或字符串),以及一个方向,这是一个枚举类型(升序 1 或降序 -1)。我有数组,也有排序方向的枚举。但是我应该在哪里/如何构建排序方法,以便像这样调用它?
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[];
答案#1
因为 TypeScript 已经加载了定义了名为 sort 的方法的基本类型,你不能用相同的名字重新定义它。如果你考虑使用一些稍微不同的名字(例如我选择 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;
}
