Typescript 将类的属性作为参数传递给可以计算该属性的函数
假设我有一个定义如下的类:Typescript 将类的属性作为参数传递给可以计算该属性的函数,typescript,Typescript,假设我有一个定义如下的类: export class test { name: string, description: string, location: string, comment: string } let data: test[] = []; data.push({'name': 'A', 'description':'Description A', 'location': 'Location 1', 'comment': 'Comment A'})
export class test {
name: string,
description: string,
location: string,
comment: string
}
let data: test[] = [];
data.push({'name': 'A', 'description':'Description A', 'location': 'Location 1', 'comment': 'Comment A'});
data.push({'name': 'B', 'description':'Description B', 'location': 'Location 1', 'comment': 'Comment B'});
data.push({'name': 'C', 'description':'Description C', 'location': 'Location 2', 'comment': 'Comment C'});
let result = this.search('location', 'Location 1'); // location, is the class attribute here
function search(attribute: string, value: string) {
let response = data.filter(a => a.attribute.includes(value);
// the attribute in a.attribute has to translate to location so the line would read as
// data.filter(a => a.location.includes(value);
return response;
}
这在typescript中可能吗?查询的结果将是数据数组的前两行。当然可以,但您也可以稍微扩展搜索功能并使其通用,这样您就可以在其中包含数据类型,如下所示:
interface Test {
name: string;
description: string;
location: string;
comment: string;
}
function Search<T, K extends keyof T>(values: T[], attribute: K, searchValue: string): T[] {
return values.filter(value => String(value[attribute]).includes(searchValue));
}
let data: Test[] = [];
data.push({'name': 'A', 'description':'Description A', 'location': 'Location 1', 'comment': 'Comment A'});
data.push({'name': 'B', 'description':'Description B', 'location': 'Location 1', 'comment': 'Comment B'});
data.push({'name': 'C', 'description':'Description C', 'location': 'Location 2', 'comment': 'Comment C'});
console.log(Search(data, 'location', 'Location 1'));
接口测试{
名称:字符串;
描述:字符串;
位置:字符串;
注释:字符串;
}
函数搜索(值:T[],属性:K,搜索值:字符串):T[]{
返回值.filter(value=>String(value[attribute])。包括(searchValue));
}
let数据:Test[]=[];
push({'name':'A','description':'description A','location':'location 1','comment':'comment A'});
push({'name':'B','description':'description B','location':'location 1','comment':'comment B'});
push({'name':'C','description':'description C','location':'location 2','comment':'comment C'});
日志(搜索(数据,“位置”,“位置1”);
数据被定义为测试
,但您似乎想要筛选不存在的属性
?您在这里给出的代码正确吗?或者您想转到[attribute]includes(value)
?@Icepickle,在查看您的答案之前,我几乎没有尝试过与评论中相同的方法!Icepickle,感谢您向我展示了一个更好的实现。@user1807337我很高兴它有帮助,我想它让我恼火的是,您必须先添加字符串转换,然后才能执行includes
,所以它可能不是完全通用的