在打字稿传递一个表达式作为过滤函数的参数
考虑下面的打字稿功能:在打字稿传递一个表达式作为过滤函数的参数
getPeople(): Person[] {
return model.people;
}
我想用嵌入式过滤器,它会工作基础上,我希望有一个表达来实现它到作为参数传递,更多或更少的这样的:
getPeopleBy(expression): Person[] {
return model.people.filter(expression);
}
var filteredPeople = getPeopleBy(p => p.age < 30);
使用LINQ和C#,我能做到通过接受一个参数与此大成Expression<Func<EcommerceProduct, bool>> filter
在Typescript/Javascript中有没有类似的东西?
否认(最初的回答 - 离开它,让别人了解进化过程):
是,在C#中,你可以这样做,但你要记住打字稿附带从C#借用一些糖语法,JavaScript是它自己的动物。
为了传递一个表达式,你需要记住lamba表达式只是一个函数,所以在JS中你只需要键,值(对象)和函数(简单,对吧?)。
所以达到你想要你的代码看起来应该是这样的:
getPeopleBy(expression: Function): Person[] {
return model.people.filter(expression);
}
var filteredPeople = getPeopleBy((p: Person) => { return p.age < 30 });
PS:可能我也建议你改变函数名getPeopleWith?
,你可以看到,从人的角度来看,它更有道理阅读:
getPeopleWith((p: Person) => { return p.age < 30 });
基本上它是让人们随着年龄小于30,任何人:)
容易阅读更新:
这将为您提供理想的结果!
class People {
private static people: any[] = [];
static where(expression: (value: any, index?: number, Array?: any[]) => boolean):
any[] {
return this.people.filter(expression);
}
}
People.where(p => p.age < 30);
更新2:
TypeScript Playground Example using interface definition for callback
如果你需要写一个FluentAPI或更大的东西和你厌倦沿callbackfn定义拖动,就可以也做这样的事情:
interface IFilter {
value: any;
index?: number;
Array?: any[];
}
class People {
private static people: any[];
static where(expression: (IFilter) => boolean): any[] {
return this.people.filter(expression);
}
}
People.where(p => p.age < 30);
更新3:
TypeScript Playground with Type Inference
而与此还可以得到很好的智能感知,通过在界面:)
interface Person {
age: number;
}
interface IFilter<T> {
value: T;
index?: number;
Array?: T[];
}
class People {
private static people: Person[];
static where(expression: (IFilter: Person) => boolean): any[] {
return this.people.filter(expression);
}
}
People.where(p => p.age < 30);
我希望这些一系列更新帮助您使用模板实现你的目标。
我看到了,基本上答案是我不能这样做...因为如果这是解决方案,我宁愿排除过滤器的方法,只是:'getPeople()。filter(x => x .age> 30)' – tocqueville
@ FrancescoLorenzetti84检查更新:) –
辉煌,谢谢 – tocqueville
查看linq.js,你可以找到更多信息here。
有了它,你可以传递一个函数作为参数用作过滤器。
谷歌搜索我发现还有一个TS库(正如我看到你正在使用TypeScript),你可以找到它here。我还没有测试过它:)
我会看看,但似乎弗拉德的答案没有额外的图书馆 – tocqueville
为什么你需要'Expression>'而不是'Func ''? –
krontogiannis
我不想传递一个函数作为参数。我想传递过滤器的表达式。 – tocqueville