Created
September 13, 2026 00:34
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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