Skip to content

How to use filter in TypeScript on different array types

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);

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?