User-defined predicates
Concept and syntax
A predicate return annotation x is T tells the checker how to narrow x when the function returns true. Implement it with reliable runtime checks. The compiler does not prove that the body actually establishes the promised type; an incorrect predicate can introduce unsoundness.
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.
function isText(x:unknown):x is string { return typeof x === "string"; }function size(x:unknown){ return isText(x) ? x.length : 0; }console.log(size("tea"),size(5));Expected output:
3 0Common mistake
Intentionally invalid; compile separately and do not execute.
function isText(x:unknown):boolean { return typeof x === "string"; }function size(x:unknown){ return isText(x) ? x.length : 0; }Expected diagnostic: TS18046. An explicit boolean result does not convey a predicate. Use a truthful x is string annotation.
Practice and recap
Write a predicate for number and filter an unknown array.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
User-defined 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)?
function isText(x:unknown):x is string { return typeof x === "string"; }function size(x:unknown){ return isText(x) ? x.length : 0; }console.log(size("tea"),size(5));Which diagnostic and explanation match the rejected example under the lesson settings?
function isText(x:unknown):boolean { return typeof x === "string"; }function size(x:unknown){ return isText(x) ? x.length : 0; }