Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

235
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda