millimoose
millimoose

Reputation: 39950

Is it possible to remove undefined from an array in a TypeScript will recognize?

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

Answers (1)

Patrick Roberts
Patrick Roberts

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

Related Questions