这是一个很长的标题,用于描述非常简单的内容。
interface Array<T> {
sortBy<T, K>(keyFunction: (t: T) => K): T[];
}
。
export namespace util {
export function sortBy<Element, Key>(array: Element[], keyFunction: (t: Element) => Key ): Element[] {
var arrayCopy = array.slice();
var mapped = arrayCopy.map(function(el, i) {
return { index: i, value: keyFunction(el) };
});
mapped.sort(function(a, b) {
return +(a.value > b.value) || +(a.value === b.value) - 1;
});
for (let i = 0; i < array.length; i++) {
let indexed = mapped[i];
array[i] = arrayCopy[indexed.index];
}
var result = mapped.map(function(el){
return arrayCopy[el.index];
});
return array;
}
}
。
Array.prototype.sortBy = function(keyFunction) {return util.sortBy(this, keyFunction)}
在这里,我正在实现MDN的一些示例代码,以数组键而不是比较函数的形式进行排序,并尝试用它修补Array原型(有关是否是个好主意的评论)。
但是,当我调用它时,Typescript无法验证键函数的正确参数类型,因此需要进行强制转换以防止编译器错误:
it('should sort in-place', () => {
var list = [{a: 'z', i: 2}, {a: 'x', i: 0}, {a: 'y', i:1}];
// all good
list.sortBy(<Function>(obj) => obj.i);
expect(list.map((obj) => obj.a)
.join('')
).toBe('xyz');
})
it('should sort in-place', () => {
var list = [{a: 'z', i: 2}, {a: 'x', i: 0}, {a: 'y', i:1}];
// Error TS2339: Property 'i' does not exist on type '{}'
list.sortBy((obj) => obj.i);
expect(list.map((obj) => obj.a)
.join('')
).toBe('xyz');
})
有什么办法可以更改此定义以起作用?有趣的是,调用util.sortBy(array, function)
(即作为函数而非方法)具有正确运行的类型参数。
您接口声明的排序功能,创建一个新的T
(sortBy<T, K>
)从断开Array
的T
。应该是sortBy<K>
和重用Array
的T
。
interface Array<T> {
sortBy<K>(keyFunction: (t: T) => K): T[];
}
var list = [{a: 'z', i: 2}, {a: 'x', i: 0}, {a: 'y', i:1}];
// Okay
list.sortBy((obj) => obj.i);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句