How to filter out nullish values from an array in TypeScript (and get the right type)
/ 1 min read
When working with arrays in TypeScript, you might want to filter out null
or undefined
values from an array. Frustratingly, something like this doesn’t work as expected:
This drives me mad and results in doing some weird type assertions to get the right type. After hitting this again today, I found a useful comment on one of the various issue threads related to this topic (source) which provides a cleaner solution:
It’s still not perfect, and doesn’t help if you have a more complex type (e.g. you are checking if x.nestedKey
is null
), but it is cleaner than some of the garbage I have come up with before.