Reputation: 39950
Is there a clean and convenient way to do something like:
const x: (string|undefined)[] = ['aaa', undefined, 'ccc'];
const y = _.filter(x, it => !!it);
so that TypeScript recognizes the type of y
as string[]
, without having to write my own function doing the filtering? (I.e. is there a way to have the language feature that narrows the type of a variable in say an if
block apply to arrays?)
Upvotes: 0
Views: 648
Reputation: 51816
Not sure why you need lodash here but yes:
const x: (string|undefined)[] = ['aaa', undefined, 'ccc'];
const y = x.filter((it): it is string => it !== undefined);
In this case, y
is inferred as type string[]
. The !!it
would also be inferred as type string[]
, but has the side-effect of also filtering out empty string entries from the array.
Upvotes: 5