Typed constructors and instance fields
Concept and syntax
A class declares instance fields and initializes them in a constructor. Annotate constructor parameters and field types to establish the invariant each new instance must satisfy. With strictPropertyInitialization, required fields must be initialized in an accepted way. Each instance maintains its own field values.
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.
class Meter {count:number;constructor(count:number){this.count=count;} read(){return this.count;}}console.log(new Meter(2).read(),new Meter(7).read());Expected output:
2 7Common mistake
Intentionally invalid; compile separately and do not execute.
class Meter {count:number;constructor(count:number){this.count=count;}}new Meter("7");Expected diagnostic: TS2345. The constructor requires a numeric count. Supply a number.
Practice and recap
Add an increment method and show that two instances keep independent counts.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Typed constructors and instance fields — 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 Meter {count:number;constructor(count:number){this.count=count;} read(){return this.count;}}console.log(new Meter(2).read(),new Meter(7).read());Which diagnostic and explanation match the rejected example under the lesson settings?
class Meter {count:number;constructor(count:number){this.count=count;}}new Meter("7");