// @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>;
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.
Most helpful comment
The type
[]means “empty tuple”, not “arbitrary array”. Indeed,arr2evaluates to
[undefined, undefined, undefined], which is not the emptytuple, so the type error is correct.
If you mean “arbitrary array”, you can write
any[], but be careful:using
anyshould be avoided whenever possible. A better type forarr2would benumber[](array ofnumbers) or(?number)[](arraywhose elements are either
numberornull/undefined). You couldalso just leave off the type annotation, and Flow will infer it.