Struggling to create a versatile function that can efficiently sort string properties of objects using String.localCompare
. However, TypeScript seems not to acknowledge that a[key]
and b[key]
should be treated as strings.
How can I resolve this issue in TypeScript?
const generateStringSort = <T>(key: keyof T) => {
return (a: T, b: T) => {
return a[key].toLowerCase().localeCompare(b[key].toLowerCase());
};
};
Error message: Property 'toLowerCase' does not exist on type 'T[keyof T]'
// sample usage
interface Item {
prop: string;
other: number;
}
const sortFunction = generateStringSort<Item>("prop");
const itemList: Item[] = [];
itemList.sort(sortFunction);