The TypeScript compiler are behaving differently if I have an union of arrays vs array of union:
type A = { x: string };
type B = { x: string, y: number };
const arr1: (A | B)[] = [];
arr1.find(e => e.x === ""); // OK
arr1.map(e => e.x); // OK
const arr2: A[] | B[] = [];
arr2.find(e => e.x === ""); // OK
arr2.map(e => e.x); // Error: Cannot invoke an expression whose type lacks a call signature.
Shouldn't this arr2.map(e => e.x) work?
This currently does not work. Since the methods of A[] and B[] have different signatures if you put them in a union the corresponding method will be a union of the original signatures and thus not invokable.
This restriction will be relaxed in a future version of typescript as described here (possibly in the January 2019 release). With the changes outlined there your example should work as expected, but at this time I have not tested this.
In the meantime your best solution is to use a type assertion:
(arr2 as (A | B)[]) .map(e => e.x);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With