The isNonNullable function is a type guard that filters out null and undefined values from an array.
I've had to do this type assertion inline so many times that I just made it into a reusable utility in most of my projects.
You can use it like this to filter out null and undefined values from an array:
const values = [1, null, 2, undefined, 3];
const nonNullableValues = values.filter(isNonNullable);
// nonNullableValues is now [1, 2, 3]Why not just use Boolean like a lot of JavaScript examples do?
Those do not provide a proper type guard, so TypeScript cannot infer that the resulting array contains only non-nullable values. Of course it also removes other falsy values like 0 and ''.
const values = [1, null, 2, undefined, 3];
const nonNullableValues = values.filter(Boolean);
nonNullableValues.map(value => value.toFixed(2)); // Error: 'value' is possibly 'null' or 'undefined'.const values = [1, null, 2, undefined, 3];
const nonNullableValues = values.filter(isNonNullable);
nonNullableValues.map(value => value.toFixed(2)); // No error, TypeScript knows values are non-nullable.Why not just use .filter(v => v != null) inline?
Well shucks... that does seem to work 😥. It used to not work which forced me to write .filter((v): v is NonNullable<typeof v> => v != null) over and over again, which is why I created the isNonNullable utility. But it seems that in TypeScript 5.5 they made improvements to type inference that now the inline v != null to work as a proper type guard.