Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

116
Views
Typescript error while array filtered on type

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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] : []);
about 4 years ago · Juan Pablo Isaza Report

0

You can use reduce method:

const myArray: number|undefined[] = []

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!