Sub topic 1
Declaring Classes and Creating Instances
A class is a reusable definition for creating related objects. It describes the data an object stores and the operations it can perform. An object created from a class is called an instance.
This chapter assumes that you know basic TypeScript types and functions, JavaScript objects, the this keyword, and the general idea of object-oriented programming.
Prerequisites
You should be able to:
- Declare variables with type annotations.
- Write and call JavaScript or TypeScript functions.
- Read object properties such as
user.name. - Explain that an object combines data with related behavior.
A class is a template
The following class describes a counter. It has a value field and an increment method:
class Counter {
value: number = 0;
increment(): void {
this.value += 1;
}
currentValue(): number {
return this.value;
}
}
const firstCounter = new Counter();
firstCounter.increment();
firstCounter.increment();
console.log(firstCounter.currentValue()); // 2The class keyword starts the declaration. The value line defines a field, which is data stored by each instance. The increment and currentValue declarations define methods, which are functions belonging to the class.
The new Counter() expression creates an instance. Each instance receives its own value field:
const firstCounter = new Counter();
const secondCounter = new Counter();
firstCounter.increment();
console.log(firstCounter.currentValue()); // 1
console.log(secondCounter.currentValue()); // 0Calling firstCounter.increment() changes only firstCounter. The two objects have the same structure and behavior, but they hold separate state.
Understanding `this`
Inside an instance method, this refers to the instance on which the method was called. Therefore, this.value means “the value field belonging to this particular counter.”
| Expression | Meaning |
|---|---|
| `Counter` | The class definition |
| `new Counter()` | A newly created instance |
| `firstCounter.value` | The field on one particular instance |
| `this.value` | The current instance's field inside a method |
Check the type of an instance
TypeScript understands that firstCounter is a Counter:
const counter: Counter = new Counter();
counter.increment();The annotation is optional here because TypeScript infers the type from new Counter(). You can use the class name as a type when a function should accept only counters:
function showCounter(counter: Counter): void {
console.log(counter.currentValue());
}Use classes when several objects need the same state and behavior. Keep each class focused on one clear responsibility.
Exercise
After const a = new Counter(); const b = new Counter(); a.increment();, what are the values of a and b?
Show answer
a has the value 1, while b remains 0 because each instance has independent state.