TypeScript 5.5: inferred type predicates fix filter(Boolean)

Posted by Panini Vyakaran · 2024-05-08

TS 5.5 finally infers type predicates. filter(Boolean) narrows correctly without a custom type guard. This one feature fixes a pain point open for 7 years. https://github.com/microsoft/TypeScript/releases/tag/v5.5.0-beta

// TypeScript 5.5 — inferred type predicates
const items: (string | null)[] = ['a', null, 'b', null, 'c'];

// Before TS 5.5: type is (string | null)[]
// After TS 5.5: type is string[] 
const filtered = items.filter(Boolean);

// Custom predicates also inferred
function isUser(x: unknown): x is User {
  return x !== null && typeof x === 'object' && 'name' in x;
}
const users = data.filter(isUser); // User[]

Explore GitVibes