Flow: Cannot assign `array.map(...)` to `arr2` because array type [1] has an unknown number of elements

Created on 5 Jun 2018  Â·  2Comments  Â·  Source: facebook/flow

reproduced here

// @flow

class Foo {
  bar: number;
}

const arr = [new Foo(), new Foo(), new Foo()];

const arr2: [] = arr.map(a => a.bar);
Cannot assign arr.map(...) to arr2 because array type [1] has an unknown number of elements, so is
incompatible with tuple type [2].

     src/main/test.js
       6│
       7│ const arr = [new Foo(), new Foo(), new Foo()];
       8│
 [2]   9│ const arr2: [] = arr.map(a => a.bar);
      10│

     /private/tmp/flow/flowlib_1af87bb1/core.js
 [1] 248│     map<U>(callbackfn: (value: T, index: number, array: Array<T>) => U, thisArg?: any): Array<U>;

Most helpful comment

The type [] means “empty tuple”, not “arbitrary array”. Indeed, arr2
evaluates to [undefined, undefined, undefined], which is not the empty
tuple, so the type error is correct.

If you mean “arbitrary array”, you can write any[], but be careful:
using any should be avoided whenever possible. A better type for
arr2 would be number[] (array of numbers) or (?number)[] (array
whose elements are either number or null/undefined). You could
also just leave off the type annotation, and Flow will infer it.

All 2 comments

The type [] means “empty tuple”, not “arbitrary array”. Indeed, arr2
evaluates to [undefined, undefined, undefined], which is not the empty
tuple, so the type error is correct.

If you mean “arbitrary array”, you can write any[], but be careful:
using any should be avoided whenever possible. A better type for
arr2 would be number[] (array of numbers) or (?number)[] (array
whose elements are either number or null/undefined). You could
also just leave off the type annotation, and Flow will infer it.

Oh sorry, I though [] was a sugar for any[]. Thanks for your help.

Was this page helpful?
0 / 5 - 0 ratings