0

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?)

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.