I’m trying to make a function that can take a generic objects key and use that to create a function to sort string properties using String.localCompare but I can’t get TypeScript to understand that a[key] and b[key] are supposed to be strings.
How do I enforce this in TS?
const makeStringSort = <T>(key: keyof T) => {
return (a: T, b: T) => {
return a[key].toLowerCase().localeCompare(b[key].toLowerCase());
};
};
Property 'toLowerCase' does not exist on type 'T[keyof T]'
// example usage
interface Item {
prop: string;
other: number;
}
const sortFn = makeStringSort<Item>("prop");
const items: Item[] = [];
items.sort(sortFn);
>Solution :
Updated answer: use mapped types
const makeStringSort = <T extends string>(key: T) => {
return <
U extends {
[Property in T]: string;
}
>(
a: U,
b: U
) => {
return a[key].toLowerCase().localeCompare(b[key].toLowerCase());
};
};