Class Programs
Class Programs — purpose and prerequisites
Classes combine state and behavior into instances. Constructor parameter properties can initialize fields concisely. Use private for compile-time access restrictions and ECMAScript #fields when runtime-enforced private access is required.
What you’ll learn
- Explain the purpose of class programs.
- Identify the typed contract, runtime responsibilities and common pitfalls.
- Run the example and extend its behavior with a practical exercise.
How the idea works
The #count field belongs to the instance and cannot be directly accessed outside its class at runtime. Calling increment twice produces 4.
TypeScript private fields are normally enforced at compile time; #private fields have JavaScript runtime semantics.
Visualize the flow
Run the checked TypeScript example
This source was compiled using TypeScript 5.8.3 with strict checking, then executed with Node.js 22.16.0. Its stdout below is the actual captured output. The core logic is runnable without a framework or a remote API; integration-specific examples appear in a separate lab when needed.
TypeScript source
class Counter {
#count = 0;
increment(by = 1): void { this.#count += by; }
value(): number { return this.#count; }
}
const counter = new Counter();
counter.increment();
counter.increment(3);
console.log(counter.value());Verified output
4Compile: npx tsc --strict --target es2022 --module commonjs class-programs.ts; run: node class-programs.js. For examples importing node: modules, install @types/node as a development dependency; for browser or React projects use the separate lab setup.
Trace the execution
The #count field belongs to the instance and cannot be directly accessed outside its class at runtime. Calling increment twice produces 4.
Before editing the code, predict what the output will be for one changed input. Run it and compare your prediction with the actual result.
Common mistake and correction
TypeScript private fields are normally enforced at compile time; #private fields have JavaScript runtime semantics.
Determine whether the issue belongs to the type system, a trust boundary, or actual runtime behavior before choosing a correction.
Your turn: extend the example
Add a decrement method that prevents the count dropping below zero and test its boundary.
Record expected success and failure outcomes, run the code, and compare the observed behavior. Keep the exercise compatible with strict type checking.
Check your understanding
Key idea to remember
The #count field belongs to the instance and cannot be directly accessed outside its class at runtime. Calling increment twice produces 4.
Apply the same reasoning to the practice task, then integrate it into a real app only when the runtime and dependency setup are ready.
Reaching the recap and completing the quizzes are separate milestones.