Sub topic 1
Declaring Classes and Creating Instances
Prerequisites
Assume you know basic TypeScript types, JavaScript functions and objects, the this keyword, and the general idea of object-oriented programming.
Declaring a Class
A class describes the data and behavior that its objects share. An object created from a class is an instance. Fields store state, constructors initialize that state, and methods define behavior.
class Account {
public readonly id: string;
private balance: number;
constructor(id: string, initialBalance: number) {
this.id = id;
this.balance = initialBalance;
}
deposit(amount: number): void {
if (amount <= 0) {
throw new Error("Amount must be positive");
}
this.balance += amount;
}
getBalance(): number {
return this.balance;
}
}
const account = new Account("a-1", 100);
account.deposit(50);
console.log(account.id); // a-1
console.log(account.getBalance()); // 150The new operator calls the constructor and returns an instance. Inside an instance method, this refers to the current object. Therefore, this.balance means the balance field belonging to that account.
Fields, Constructors, and Strict Initialization
A field declaration gives a property a type. You can initialize it where it is declared or assign it in every constructor path.
With strictPropertyInitialization, TypeScript reports an error when a field might remain undefined. The definite-assignment assertion, written !, tells TypeScript that another initialization process guarantees the field will be assigned. Use it only when that guarantee is real.
class User {
name = "Guest";
email: string;
token!: string;
constructor(email: string) {
this.email = email;
}
loadToken(): void {
this.token = "temporary-token";
}
}Prefer ordinary initialization when possible. A forgotten assignment to a ! field can still produce an undefined value at runtime.
Controlling Access
public is the default and permits access from anywhere. private permits access only inside the declaring class. protected permits access inside the class and its subclasses.
These modifiers primarily protect code during type checking. They define the public API and prevent callers from changing implementation details directly.
Exercise
Why does account.balance = 0 fail in the example?
Show answer
balance is private, so code outside Account cannot access or change it directly.