Inferred predicates
Concept and syntax
TypeScript 5.5 and later can infer predicates for suitable functions, including a single return expressing a narrowing test with no parameter mutation and no explicit return annotation. Filtering a union with such a predicate may produce a narrower array. A broad boolean annotation can prevent this inference.
Working example
Save each snippet separately as main.ts in a fresh directory. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts, then run the accepted example with node main.js. Forced module detection isolates snippet names from global declarations.
const values:(number|undefined)[]=[0,undefined,7];const present:number[]=values.filter(x=>x!==undefined);console.log(present.join(","));Expected output:
0,7The predicate excludes only undefined. Zero remains a valid number, so the filtered array contains 0 and 7. The assignment to number[] is part of the compile-time verification.
Common mistake
Intentionally invalid; compile separately and do not execute.
const values:(number|undefined)[]=[0,undefined,7];const present:number[]=values.filter((x):boolean=>x!==undefined);Expected diagnostic: TS2322. The explicit boolean annotation loses the predicate. Remove it or declare a correct predicate.
Practice and recap
Compare filtering with x !== undefined and Boolean for an array containing zero.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Inferred predicates — knowledge check
Check the contract, trace output, and diagnose an invalid example.
Which statement about this lesson’s concept is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
const values:(number|undefined)[]=[0,undefined,7];const present:number[]=values.filter(x=>x!==undefined);console.log(present.join(","));Which diagnostic and explanation match the rejected example under the lesson settings?
const values:(number|undefined)[]=[0,undefined,7];const present:number[]=values.filter((x):boolean=>x!==undefined);