否认(最初的回答 - 离开它,让别人了解进化过程):
是,在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,任何人:)
容易阅读
更新:
这将为您提供理想的结果!
TypeScript Playground Example
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);
我希望这些一系列更新帮助您使用模板实现你的目标。
为什么你需要'Expression>'而不是'Func ''? –
krontogiannis
我不想传递一个函数作为参数。我想传递过滤器的表达式。 – tocqueville