gpt4 book ai didi

typescript - 将类的属性作为参数传递给可以评估该属性的函数

转载 作者:行者123 更新时间:2023-12-04 10:01:22 26 4
gpt4 key购买 nike

假设我有一个定义如下的类:

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'));

关于typescript - 将类的属性作为参数传递给可以评估该属性的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61805371/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com