I'm encountering an issue with my TypeScript code that appears in multiple places:
(Take note of the code snippet on the typescript playground)
let filtered = items.filter(item =>
item.title.toLowerCase().includes(search.toLowerCase()) ||
item.name.toLowerCase().includes(search.toLowerCase()) ||
item.date.toLowerCase().includes(search.toLowerCase())
);
This led me to develop the following function
function filterByKey<T, K extends keyof T>(items: T[], keys: K[], search: string) {
return items.filter((item) =>
keys.some((key) => item[key].toString().toLowerCase().includes(search.toLowerCase()))
);
}
which I intend to use like this:
let filtered = filterByKey(items, ['title', 'name', 'date'], search));
However, I'm facing this error:
Property 'toString' does not exist on type 'T[K]'
I attempted the following approach, but it doesn't seem to be a valid syntax
function filterByKey<T, K extends keyof T, T[K] extends string>(items: T[], keys: K[], search: string)
Is there a way to inform TypeScript that the properties of items will support .toString()
?
Alternatively, how would you suggest handling such a scenario to prevent TypeScript from raising complaints?
I referenced the TypeScript documentation here: https://www.typescriptlang.org/docs/handbook/2/generics.html#using-type-parameters-in-generic-constraints