简体   繁体   中英

How to use a generic type annotation inside a function in Facebook Flow

Is is possible to use Flow's generic type annotation inside a function? For example, to filter items based on whether they are of the generic type.

// @flow
class Base {}

function filterItems<T>(items: Base[]) {
  return items.filter(x => /* How to filter for 'x is T' here?*/);
}

So, the outcome of the following code, a would be an array containing a single Foo .

class Foo extends Base {}
const a = filter<Foo>([new Base(), new Foo()]);  

Flowtype is an annotation-only syntax. Converting Flowtype code to JavaScript only involves deleting the annotations. This means that what you're asking is not possible, because the types do not exist at runtime.

To do what you want, I'd recommend just doing normal JS like this:

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;
  }, []);
}

and

const a = filter(Foo, [new Base(), new Foo()]);  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM