Property #39;toLowerCase#39; does not exist on type #39;T[keyof T]#39;(类型#39;T[key of T]#39;上不存在属性#39;toLowerCase#39;)
问题描述
我正在尝试编写带有泛型类型的函数,该函数采用两个参数(obj数组和搜索词),但遇到错误-属性"toLowerCase"在类型"T[keyof T]"上不存在
下面是函数:
function matchSearchTerm<T>(data: T[], search: string): T[] {
return data.filter((obj) => {
const filteredData = (Object.keys(obj) as Array<keyof typeof obj>).some((value) => {
return (
typeof obj[value] === "string" && obj[value].toLowerCase().includes(search.toLowerCase())
);
});
return filteredData;
});
}
这里缺少什么?
推荐答案
似乎与此问题有关:https://github.com/microsoft/TypeScript/issues/10530
您仍然可以将obj[value]
拉出到变量中以获得类型推断:
function matchSearchTerm<T>(data: T[], search: string): T[] {
return data.filter((obj) => {
const filteredData = (Object.keys(obj) as Array<keyof typeof obj>).some((value) => {
const val = obj[value];
return (
typeof val === "string" && val.toLowerCase().includes(search.toLowerCase())
);
});
return filteredData;
});
}
这篇关于类型';T[key of T]';上不存在属性';toLowerCase';的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!