Definite assignment and initialization
Concept and syntax
Required instance fields need an initializer or a constructor assignment recognized by the checker. A definite assignment assertion field!: T tells it to trust later initialization, but does not create the promised value. Prefer constructor initialization; use assertions only when an external lifecycle truly guarantees it.
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.
class Ready {count:number;constructor(n:number){this.count=n;}}class Assumed {count!:number;}console.log(new Ready(7).count,new Assumed().count===undefined);Expected output:
7 trueCommon mistake
Intentionally invalid; compile separately and do not execute.
Expected diagnostic: TS2564. count is not definitely initialized. Set it in the constructor or give it a default.
Practice and recap
Add a constructor branch that forgets initialization and observe the diagnostic.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Definite assignment and initialization — 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)?
class Ready {count:number;constructor(n:number){this.count=n;}}class Assumed {count!:number;}console.log(new Ready(7).count,new Assumed().count===undefined);Which diagnostic and explanation match the rejected example under the lesson settings?
class Missing {count:number;}new Missing();