我有一个uniqBy
这样定义的函数:
export function uniqBy<T>(a: T[], key: any): T[] {
const seen = {};
return a.filter(function (item) {
if (item) {
const k = key(item);
return seen.hasOwnProperty(k) ? false : (seen[k] = true);
} else {
return false;
}
});
}
这会根据输入数组强类型化我的返回值,但我也希望key
参数是强类型化的,这样如果我尝试传入不存在的属性时会出现编译时错误T
。当前使用示例:
uniqArray = uniqBy(this._checkups, x => x.CatDescription);
_checkups
是以下数组:
export interface Checkup {
id: string;
CatDescription: string;
ProcessTitle: string;
MsgProcessID: number;
MsgDate: string;
MsgStatus: number;
MsgText: string;
MsgAction: string;
MsgEntityID: string;
MsgEntity: string;
}
如果尝试执行以下操作,我希望它:
uniqArray = uniqBy(this._checkups, x => x.NonExistantProperty);
给了我一个编译时错误(以及属性完成时的 IntelliSense)。key
为了做到这一点,我将如何在参数中定义?
这将返回一个只有唯一值的项目数组(在重复的情况下CatDescription
使用第一个对象)。CatDescription
我不知道这叫什么,它不是Predicate<T>
用于过滤并返回布尔值的。