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

236
Vistas
Array has possibly undefined elements even if i filter it

I have this code:

enter image description here

I have copy pasted an image so you can see the type what typescript inherit.

DataStore.query() returns undefined or User. At the end i filter the result with .filter(Boolean) so that there is no undefined in it.

Why does typescript still inherit it as (User | undefined)[] while its not possible that some elements are undefined?

My expectation is: let users: User[]

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Typescript isn't that smart in detecting what your predicate for the filter is actually doing since you can pass an arbitrary predicate. If you want more precise typing inference, you can add a type guard on your predicate to help TS understand what it does https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates

For example,

let users: (number | undefined)[] = [];
// TS will infer `usersFilteredA` to (number | undefined)[]
let usersFilteredA = users.filter((user) => user !== undefined);
// TS will infer `usersFilteredB` to number[]
let usersFilteredB = users.filter((user): user is number => user !== undefined);

From what I can tell, TS will evaluate the type of each array element within the scope of each predicate and then override the type of the array object.

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