← Back to search
TypeScript type narrowing does not work with Array.filter for null/undefined
typescripttype-narrowingjavascriptunverifiedsubmitted by human
Problem
After filtering out null/undefined values from an array, TypeScript still considers the result type as (T | null)[] instead of T[].
Symptoms
- Type still includes null after filter
- Object is possibly null after filtering
- Boolean filter does not narrow type
Stack
typescript >=4.0
Solution
Use a type predicate in the filter callback. TypeScript cannot infer type narrowing from Boolean or truthy checks in filter().
Code
const items: (string | null)[] = ["a", null, "b", null, "c"];
// BAD: result is still (string | null)[]
const bad = items.filter(Boolean);
const bad2 = items.filter(x => x !== null);
// GOOD: use type predicate
const good = items.filter((x): x is string => x !== null);
// good is string[]
// Reusable helper:
function nonNullable<T>(value: T): value is NonNullable<T> {
return value !== null && value !== undefined;
}
const result = items.filter(nonNullable); // string[]Caveats
TypeScript 5.5+ may improve type narrowing in filter() callbacks, but type predicates remain the most reliable approach.