Rob*_*n_f 4 generics typescript
我正在尝试使用 TypeScript 编写一个函数,该函数将允许我根据对象的类型过滤对象列表。结果应该是一个允许我执行以下任一操作的函数:
filter<Foo>(items);
Run Code Online (Sandbox Code Playgroud)
或者
filter(items, Foo);
Run Code Online (Sandbox Code Playgroud)
我一直在尝试通过以下方式做到这一点:
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));
Run Code Online (Sandbox Code Playgroud)
但这不起作用。
我怎样才能使这项工作?
当您传入类型时,您实际上是在传入类的构造函数。您的签名正在传递T. 你应该试试:
const filter = <T extends Foo>(items: any[], typeT: new (...params : any[]) => T): T[] => {
return items.filter(item => item instanceof typeT)
};
Run Code Online (Sandbox Code Playgroud)
注意:在您的示例中,数组中的所有项目都将通过过滤器,因为Bar派生自Foo,因此也是Foo. 如果你只想要类型的对象Foo而不是派生的,你可以使用item.constructor == typeT
| 归档时间: |
|
| 查看次数: |
5252 次 |
| 最近记录: |