是否可以在函数内使用Flow的泛型类型注释?例如,根据项目是否为泛型类型来过滤项目。
// @flow
class Base {}
function filterItems<T>(items: Base[]) {
return items.filter(x => /* How to filter for 'x is T' here?*/);
}
因此,以下代码的结果a
将是一个包含单个Foo
的数组。
class Foo extends Base {}
const a = filter<Foo>([new Base(), new Foo()]);
答案 0 :(得分:4)
Flowtype是一种仅注释语法。将Flowtype代码转换为JavaScript仅涉及删除注释。这意味着你所要求的是不可能的,因为这些类型在运行时不存在。
为了做你想做的事,我建议你做这样的普通JS:
function filter<T: Base>(type: Class<T>, items: Array<Base>): Array<T> {
return items.reduce((acc, item) => {
if (item instanceof type) acc.push(item);
return acc;
}, []);
}
和
const a = filter(Foo, [new Base(), new Foo()]);