[英]Property 'toLowerCase' does not exist on type 'T[keyof T]'
I am trying to write a function with generic types which takes two args (array of obj and search term) but I am getting an error - Property 'toLowerCase' does not exist on type 'T[keyof T]'我正在尝试编写一个带有泛型类型的 function,它需要两个 args(obj 数组和搜索词),但我收到一个错误 -类型 'T[keyof T]' 上不存在属性 'toLowerCase'
here is the function:这是 function:
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;
});
}
What is missing here?这里缺少什么?
Seems related to this issue: https://github.com/microsoft/TypeScript/issues/10530似乎与此问题有关: https://github.com/microsoft/TypeScript/issues/10530
You can still pull the obj[value]
out into a variable to get the type inference:您仍然可以将
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;
});
}
function matchSearchTerm<T extends Record<string, string>>(data: T[], search: string) {
return data.filter((obj) => {
const filteredData = (Object.keys(obj) as Array<keyof T>).some((value) => {
const checkIt = obj[value]
type O = typeof checkIt
return (
typeof obj[value] === "string" && obj[value].toLowerCase().includes(search.toLowerCase())
);
});
return filteredData;
});
}
Just add extra constraint to your T
generic parameter: T extends Record<string, string>
只需为您的
T
泛型参数添加额外的约束: T extends Record<string, string>
How about this:这个怎么样:
return obj[value]['toLowerCase']?.call(obj[value]).includes(search.toLowerCase())
in my eyes its returning true/false/undefined -> for filters its fine... or we can use some ternary operator, if we want just true/false....在我看来,它返回 true/false/undefined -> for filters 它很好......或者我们可以使用一些三元运算符,如果我们只想要 true/false......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.