Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

114
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda