0

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[]

bill.gates
  • 14,145
  • 3
  • 19
  • 47
  • Don't post images of code, take the time to include the relevant code as text to make it easier to answer. – pilchard Jun 29 '22 at 21:43

1 Answers1

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.

Jason
  • 1