我正在尝试使用TypeScript编写一个函数,该函数将允许我根据对象类型过滤列表。结果应该是一个函数,使我能够执行以下操作:
filter<Foo>(items);
或者
filter(items, Foo);
我一直在尝试以下方法进行操作:
class Foo {
public constructor(public name: string, public type: string) {
}
}
class Bar extends Foo { }
const items: Foo[] = [
new Foo('Foo', 'A'),
new Bar('bar', 'A'),
new Foo('baz', 'B'),
];
const filter = <T extends Foo>(items: any[], typeT: T): T[] => {
return items.filter(item => item instanceof typeT)
};
console.log(filter(items, Foo));
但是这个方法不起作用。
我该如何让它起作用?