Home > Mobile >  Typescript error while array filtered on type
Typescript error while array filtered on type

Time:02-20

I have an array of number | undefineds and I want the max of this array, if any of them is a number. In order to do so I want to filter on the element being of type number, so that I can pass a numbers-only array to Math.max(...array)

(I know I shouldn't Math.max on an desctructured empty array, so I'll only do a math.max if there are 1 or more numeric values in the array)

const numbersArray: number[] = [a,b].filter((v) => typeof v === "number");

That works fine in runtime, but I get a typescript error saying that I cant assert numbersArray to be of type number[].

Type 'undefined[]' is not assignable to type 'number[]'.
  Type 'undefined' is not assignable to type 'number'.ts(2322)

What am I doing wrong here?

CodePudding user response:

Unfortunately typescript doesn't understand filter for some reason.

The usual solution would be to do a typecast

const numbersArray: number[] = [1, undefined, 3].filter((v): v is number => typeof v === "number");

However for some reason typescript understands flatMap so you can use that as an alternative. Just beware that IE doesn't support it natively so it needs to be transplied if you're aiming to support it.

const numbersArray: number[] = [1, undefined, 3].flatMap(v => typeof v === "number" ? [v] : []);

CodePudding user response:

You can use reduce method:

const myArray: number|undefined[] = []

let filteredArray: number[]  = []
filteredArray = myArray.reduce<number[]>((previous, current) => current ? [...previous, current] : previous, [])

  • Related