In my codebase, I have a custom function called uniqBy
, which filters out duplicate items based on a specified key:
export function uniqBy<T>(array: T[], key: any): T[] {
const seen = {};
return array.filter(function (item) {
if (item) {
const k = key(item);
return seen.hasOwnProperty(k) ? false : (seen[k] = true);
} else {
return false;
}
});
}
The current implementation enforces strong typing for the input array, but I also want to ensure that the key
parameter is strongly typed. This way, I can catch errors at compile time if I try to pass in a property that doesn't exist on type T
.
For example, here's how it is currently used:
uniqArray = uniqBy(this._checkups, x => x.CatDescription);
Where _checkups
is an array of objects defined by the Checkup
interface:
export interface Checkup {
id: string;
CatDescription: string;
ProcessTitle: string;
MsgProcessID: number;
MsgDate: string;
MsgStatus: number;
MsgText: string;
MsgAction: string;
MsgEntityID: string;
MsgEntity: string;
}
I want to receive a compile-time error and have IntelliSense support when attempting something like this:
uniqArray = uniqBy(this._checkups, x => x.NonExistantProperty);
How should I define the key
parameter in the function signature to achieve this requirement?
The goal is to get an array with unique values of the CatDescription
property, keeping only the first occurrence in case of duplicates.
I am looking for guidance on specifying the correct type for the key
parameter to enable this behavior, as it differs from a traditional Predicate<T>
.