Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 215
HelloWorld Avatar asked Aug 05 '26 01:08

HelloWorld


2 Answers

function foo(): (number|string)[]

For same reason as here: Typescript: How to map over union array type?

like image 121
Vulwsztyn Avatar answered Aug 07 '26 15:08

Vulwsztyn


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.

like image 34
Lars Avatar answered Aug 07 '26 15:08

Lars