Classes and Object-Oriented TypeScriptLesson 5.1
TypeScript class basics access modifiers public private protected
class declaration, constructor syntax, public modifier, private modifier, protected modifier, readonly modifier, parameter properties
Access modifiers
TypeScript adds access control keywords absent from standard JavaScript:
class BankAccount {
public owner: string;
private balance: number;
protected accountType: string;
readonly id: string;
constructor(owner: string, balance: number) {
this.owner = owner;
this.balance = balance;
this.accountType = "checking";
this.id = crypto.randomUUID();
}
deposit(amount: number): void {
this.balance += amount;
}
getBalance(): number {
return this.balance;
}
}Parameter properties shorthand
Declare and assign constructor params in one line:
class User {
constructor(
public name: string,
private email: string,
readonly id: number
) {}
}
// Equivalent to declaring and assigning all three in bodyAccess modifiers are compile-time only โ JavaScript's private fields (#) provide actual runtime privacy if needed.
