I have this code:
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[]
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.