Take a look at this function:
function getArray(): string[] | number[] {
return [];
}
To keep it short, when I execute the following code:
getArray().forEach(item => console.log(item));
I encounter this error from the compiler:
TS2349 Cannot invoke expression whose type lacks a call signature.
What could be causing this issue? From my perspective, it seems like forEach
should work without any problems because the function definitely returns an array. However, the IntelliSense suggests the method, but when selected, the error appears in the output.
Is this a bug or am I overlooking something simple?
Edit: Although there are some alternatives like returning Array<string | number>
or using overloads, I'm specifically interested in understanding why returning a union of two array types prevents method invocation.
We can confirm that the returned type is an array containing elements of type string | number
.