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

238
Views
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 answers
Answer question

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 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!