Skip to content

Instantly share code, notes, and snippets.

@dantman
Last active October 10, 2026 12:46
Show Gist options
  • Select an option

  • Save dantman/eba6c20c8e10a3ce217d99a1cee93084 to your computer and use it in GitHub Desktop.

Select an option

Save dantman/eba6c20c8e10a3ce217d99a1cee93084 to your computer and use it in GitHub Desktop.
isNonNullable utility, allows you to simply write .filter(isNonNullable) on an array to exclude null/undefined and get the correct array type as a result.

isNonNullable

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.

/**
* Type guard to check if a value is non-nullable.
*
* This is useful for filtering out null and undefined values from arrays.
* Unlike Boolean this will only filter out null and undefined values and the type of the value will be narrowed accordingly.
*
* @param value The value to check.
* @returns True if the value is not null or undefined, false otherwise.
*
* @example If condition
* ```ts
* if (isNonNullable(value)) {
* // Value is now narrowed to exclude null and undefined
* }
* ```
*
* @example Filtering an array
* ```ts
* const values = [1, null, 2, undefined, 3];
* const nonNullableValues = values.filter(isNonNullable);
* // nonNullableValues is now [1, 2, 3]
* ```
*/
export function isNonNullable<T>(value: T): value is NonNullable<T> {
return value != null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment