Roadmap › TypeScript — Types, Generics and Real-World Patterns › Module: Classes and Generics
Lessons in this course (9)
4. Classes, access modifiers and enums
Intermediate★ Must knowLesson 4 of 9
typescript
abstract class Account {
private static nextId = 1;
readonly id = Account.nextId++;
constructor(public owner: string, protected balance = 0) {} // parameter properties
deposit(amount: number) { if (amount <= 0) throw new Error("Invalid"); this.balance += amount; }
abstract monthlyFee(): number;
}
class Savings extends Account implements Printable {
monthlyFee() { return this.balance > 10_000 ? 0 : 5; }
print() { return `${this.owner}: ${this.balance}`; }
}
interface Printable { print(): string; }
// enum vs union
enum Role { Admin = "ADMIN", User = "USER" } // generates runtime JS object
type RoleU = "ADMIN" | "USER"; // zero runtime cost — usually preferredprivate(TS-only, compile-time) vs#field(JavaScript private, enforced at runtime).readonlyvsconst:readonlyfor properties,constfor variables.implementschecks a class matches an interface; it doesn't add code.