1

我有一个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>用于过滤并返回布尔值的。

4

1 回答 1

2

似乎作为第二个参数传递回调,但你没有它的类型,所以你只需给它一个类型(val: T) => T[keyof T]

export function uniqBy<T>(a: T[], key: (val: T) => T[keyof T]): 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;
        }
    });
}

然后通过添加不存在的键它会给你一个错误

uniqArray = uniqBy<Checkup>(this._checkups, x => x.NonExistantProperty);
于 2021-03-16T19:38:22.120 回答