Please consider the following function:
function getArray(): string[] | number[] {
return [];
}
Long story short, when I do this:
getArray().forEach(item => console.log(item));
The compiler gives me this:
TS2349 Cannot invoke expression whose type lacks a call signature.
Why is this happening? They way I see it, forEach should be able to be called here without errors, as as far as the compiler is concerned, it is certain that an array will be returned. What is interesting is that IntelliSense will offer autocompletion for this method as usual, but after going with the autocomplete suggestion the error message will show in output.
Is this a bug, or am I missing something trivial here?
Edit: I could use various workarounds, like returning Array<string | number> instead, or using overloads, but I'm particularly interested in why returning an union of two array types disallow method invocation.
It is certain that the type is an array, with elements of type string | number.