I wrote a simple function in TypeScript that sorts an array of objects based on one of their property. The code looks like:
export const mySortFunction = (sortKey: string, invert: boolean) => {
return (a: any, b: any) => {
if (a[sortKey] < b[sortKey]) {
return invert ? 1 : -1;
} else if (a[sortKey] > b[sortKey]) {
return invert ? -1 : 1;
}
return 0;
}
}
Then, if I have a type Person, with name and lastname properties, I can sort the list of persons with a call like persons.sort(mySortFunction('name', true)) or persons.sort(mySortFunction('lastname', false)).
The function is working, but I'm not really happy with the typing here. Basically, I want to have something like:
export const mySortFunction = <T>(sortKey: string, invert: boolean) => {
return (a: T, b: T) => {
...
}
}
and indicates to TypeScript that T should extends a type that has a key which matches the value of sortKey...
How can I set a good typing for my function signature?