Non-null assertion
Concept and syntax
The postfix non-null assertion x! removes null and undefined from the checked type without performing a runtime check. If the value is absent, the next operation may fail. Prefer explicit guards or an assertion function that actually throws when the invariant is false.
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.
The accepted example deliberately exposes a static-safety limitation. Do not imitate the unsafe path in production.
function risky(x:string|null){return x!.length;}function safe(x:string|null){return x===null?0:x.length;}console.log(safe(null),safe("tea"));try{risky(null);}catch{console.log("failed");}Expected output:
0 3failedCommon mistake
Intentionally invalid; compile separately and do not execute.
Expected diagnostic: TS18047. The value may be null. Check it explicitly rather than adding ! blindly.
Practice and recap
Replace risky with a guard that throws a descriptive error.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Non-null assertion — 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 risky(x:string|null){return x!.length;}function safe(x:string|null){return x===null?0:x.length;}console.log(safe(null),safe("tea"));try{risky(null);}catch{console.log("failed");}Which diagnostic and explanation match the rejected example under the lesson settings?
function size(x:string|null){return x.length;}