How do user-defined type predicates interact with strictNullChecks when narrowing away null specifically (as opposed to a broader type check)?
Short answer
A type predicate function like `(value): value is T` can specifically be written to narrow away JUST null (or undefined) from a broader union, which is especially useful as a reusable, named alternative to writing the same `!== null` check inline repeatedly across a codebase…
Advertisement
AModel answer
A type predicate function like `(value): value is T` can specifically be written to narrow away JUST null (or undefined) from a broader union, which is especially useful as a reusable, named alternative to writing the same `!== null` check inline repeatedly across a codebase, particularly inside array methods like .filter() where inline narrowing doesn't otherwise propagate to the resulting array's type.
function isNotNull<T>(value: T | null): value is T {
return value !== null;
}
const maybeUsers: (User | null)[] = [user1, null, user2];
const users: User[] = maybeUsers.filter(isNotNull); // correctly typed as User[], not (User | null)[]Real-world example
Filtering out null entries from an array while getting the compiler to correctly recognize the result no longer contains null, unlike a plain inline filter callback.
Likely follow-ups
- Why does `maybeUsers.filter(u => u !== null)` NOT automatically produce a User[] result the way the isNotNull predicate does?
Related topics