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:
const values = [1, null, 2, undefined, 3];const filtered = values.filter( (value) => value !== null && value !== undefined,); // Type is (number | null | undefined)[]
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:
values.filter((x): x is NonNullable<typeof x> => Boolean(x));
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.