[英]How can I pass an attribute as a parameter with Typescript?
I am a newbie with Angular 8.我是 Angular 8 的新手。
I would like to pass an array of interfaces to a sort function, and I would like to pass interface attributes as parameters.我想将接口数组传递给排序函数,并且我想将接口属性作为参数传递。
For now I have tried this way:现在我已经尝试过这种方式:
sortBy<T, K keyof T>(field: K, arr: T[], mode: 'Asc' | 'Desc'): T[] {
const res = arr.sort((x, y) => x[field].localCompare(y[field], undefined, { sesitivity: 'base' }));
return mode === 'Asc'
? res
: res.reverse();
}
But I am noticing that the editor (VSCode) is reporting to me some inaccuracies, in particular:但我注意到编辑器 (VSCode) 向我报告了一些不准确之处,特别是:
I can't decipher these comments.我无法解读这些评论。 What should I do to optimize my function?我应该怎么做才能优化我的功能?
您不需要 K 参数:
sortBy<T>(field: keyOf T, arr: T[], mode: 'Asc' | 'Desc'): T[]
In your case, field is typed as an object k, and ofc, you cannot use an object as index.在您的情况下,字段被键入为对象 k,并且 ofc,您不能使用对象作为索引。 If you wanna call a parameter, you have 2 options :如果你想调用一个参数,你有两个选择:
const x = object.param;
Or或者
const x = object['param'];
In your case, your param 'field' need to be a string, then you will be able to do:在您的情况下,您的参数“字段”需要是一个字符串,然后您将能够执行以下操作:
x[field]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.