Given is the function signature below:
function foo(): string[] | number[]
Why does TS complain about the follow function call of filter?
foo().filter((v) => true);
^^^^^^
Error
This expression is not callable. Each member of the union type '{ (predicate: (value: number, index: number, array: number[]) => value is S, thisArg?: any): S[]; (predicate: (value: number, index: number, array: number[]) => unknown, thisArg?: any): number[]; } | { ...; }' has signatures, but none of those signatures are compatible with each other.
Of course I can cast it to [], but what is the proper way here? The error message is very difficult to understand? How would one decipher this?
Example: Playground
function foo(): (number|string)[]
For same reason as here: Typescript: How to map over union array type?
Probably because the first argument of the .filter() method is typed in TS to have the type of the items in the array. Since your function is basically "returning" .filter((v: number)): number[] | filter((v: string)): string[] the two signatures are incompatible.
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