Flow: Flow Type for mixed array

Created on 27 Oct 2017  路  6Comments  路  Source: facebook/flow

type A = {
  name: string,
  city: string,
  address: string,
};
type B = {
  name: string,
  store_name: string,
  city: string,
  lat: number,
  lng: number,
};

i have a variable c: A[] | B[], when I try to use c.forEach or c.map, flow complains. the complete example in the flow try below: Flow Try

Most helpful comment

You should specify that you will not modify array.

function doSomething(c: $ReadOnlyArray<A|B>) {
  c.map(cc => {
    return cc.name;
  });
}

Flow Try

All 6 comments

I understand that flow might want to complain on the map because it can't know which Array is being mapped on, but if I refine the type like so I think it should work but doesn't.

function doSomething(c: A[] | B[]) {
  if (c.length > 0) {
    const a1: A | B = c[0]
    if (a1.lat) {
      // Flow should know that c is B[] now
      c.map(cc => {
          return cc;
        });
      }
  }
}

Flow Try

You should specify that you will not modify array.

function doSomething(c: $ReadOnlyArray<A|B>) {
  c.map(cc => {
    return cc.name;
  });
}

Flow Try

@yury I couldn't find docs related to $ReadOnlyArray, do you know where I can read up about it?

@tanhauhau

The problem with original example is that (A|B)[] is expected, but A[] | B[] is passed instead.

@yury鈥榓 suggestion of using $ReadOnlyArray fixed my example!

Was this page helpful?
0 / 5 - 0 ratings