Typed arrays and union types
There has always been an issue in invoking unions of functions. Until recently the rule was that no invocation would be allowed at all, but since 3.3 (PR) invocation is allowed with some caveats. The big one you are hitting here is that if the constituents of the union both have generic signatures the call will still not be allowed. So for example on simple arrays one forEach
can be called (no generic type parameters on it), while reduce
can't be called (since both reduce
from string[]
and from number[]
have a generic type parameter):
declare let o: string[] | number[];
o.forEach((e: number | string) => console.log(e)); // ok
o.reduce((e: number | string, r: number | string) => e + ' ' + r) //err
This does mean having a union of array types is difficult to use and only allows invocation of a very small set of methods (most Array methods have generic type parameters).
This also applies to Uint8Array
and Int8Array
which while don't inherit array have most of the same methods.
There is no good solution here, the simplest work around is to assert the variable to one of the types and go with that (assuming you don't use the array
callback parameter it should be ok)
const f3 = (arr: T3) => (arr as Uint8Array).reduce((sum, value, array /* no good inferred to Uint8Array */) => sum + value);
Or fall back to one of the functions you can invoke
const f4 = (arr: T3) => {
let sum = 0;
(arr as Uint8Array).forEach((val)=> sum + val)
}