Assertion functions
Concept and syntax
An assertion function with return type asserts x is T promises that normal return establishes T. Throw when the check fails; otherwise later code treats the argument as narrowed. Unlike a boolean predicate, callers need not write an if branch. Do not assert facts without checking them.
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 requireText(x:unknown):asserts x is string { if(typeof x!=="string") throw new Error("text required"); }function size(x:unknown){ requireText(x); return x.length; }console.log(size("tea"));try { size(5); } catch { console.log("rejected"); }Expected output:
3rejectedCommon mistake
Intentionally invalid; compile separately and do not execute.
function requireText(x:unknown):void { if(typeof x!=="string") throw new Error("text required"); }function size(x:unknown){ requireText(x); return x.length; }Expected diagnostic: TS18046. void does not communicate the postcondition. Declare the assertion signature and check it.
Practice and recap
Create a number assertion and test both accepted and rejected inputs.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Assertion functions — 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 requireText(x:unknown):asserts x is string { if(typeof x!=="string") throw new Error("text required"); }function size(x:unknown){ requireText(x); return x.length; }console.log(size("tea"));try { size(5); } catch { console.log("rejected"); }Which diagnostic and explanation match the rejected example under the lesson settings?
function requireText(x:unknown):void { if(typeof x!=="string") throw new Error("text required"); }function size(x:unknown){ requireText(x); return x.length; }