isNonNullable()
isNonNullable<
T>(value):value is NonNullable<T>
Checks if a value is not null or undefined.
💎 Why is this a Hidden Gem?
A powerful utility that filters out both null and undefined, narrowing types effectively.
remarque
Narrows T to NonNullable<T>. Uses loose equality (!= null) to check both.
Type Parameters
T: T
The type of the value.
Parameters
value: T
The value to check.
Returns: value is NonNullable<T>
true if the value is not null or undefined, false otherwise.
See Also
Since
2.0.0
Example
isNonNullable('hello'); // => true
isNonNullable(0); // => true
isNonNullable(false); // => true
isNonNullable(null); // => false
isNonNullable(undefined); // => false
How it works?
Type guard that checks if a value is not null or undefined.
Type Narrowing
Common Checks
| Value | Result |
|---|---|
0 | true |
'' | true |
false | true |
NaN | true |
null | false |
undefined | false |
Comparison
| Guard | Excludes |
|---|---|
isNonNull | null |
isNonUndefined | undefined |
isNonNullable | null AND undefined |
Use Cases
Filter missing values 📌
Remove null and undefined from arrays while narrowing types.
Perfect for cleaning data lists before processing.
const items = [1, null, 2, undefined, 3];
const cleanItems = items.filter(isNonNullable); // Type is number[]
Chain with optional access
Combine with optional chaining for clean null-safe pipelines.
const userNames = users
.map(u => u.profile?.displayName)
.filter(isNonNullable);
// Type: string[] (no undefined)
true
false