How to use filter in TypeScript on different array types

Viewed 2539

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

2 Answers

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.

Related