Classes
Classes in TypeScript
TypeScript classes are a superset of ES2015 classes, adding access modifiers, readonly properties, and full type checking.
Constructor and fields Declare fields on the class body and initialize them in the constructor. TypeScript infers field types from assignments, but explicit annotations are clearer.
Access modifiers
public– accessible everywhere (default).private– accessible only within the declaring class.protected– accessible within the declaring class and subclasses.
Parameter shorthand Prefix constructor parameters with access modifiers to declare and initialize fields in one step:
constructor(private name: string, public age: number) {}readonly
A readonly field may only be assigned in the declaration or the constructor.
Methods
Methods are functions attached to the class. They can use this to access other members. Return types and parameter types follow the same rules as regular functions.
Code Examples
class BankAccount {
readonly accountNumber: string;
private balance: number;
public owner: string;
constructor(accountNumber: string, owner: string, initialBalance: number) {
this.accountNumber = accountNumber;
this.owner = owner;
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 acc = new BankAccount("ACC-001", "Alice", 1000);
acc.deposit(500);
console.log(`${acc.owner} | ${acc.accountNumber} | Balance: ${acc.getBalance()}`);private restricts balance to inside the class; readonly prevents accountNumber from being changed after construction.
class Point {
constructor(public x: number, public y: number) {}
distanceTo(other: Point): number {
return Math.sqrt((this.x - other.x) ** 2 + (this.y - other.y) ** 2);
}
toString(): string {
return `(${this.x}, ${this.y})`;
}
}
const p1 = new Point(0, 0);
const p2 = new Point(3, 4);
console.log(p1.toString());
console.log(p2.toString());
console.log(p1.distanceTo(p2));Parameter properties eliminate boilerplate by declaring and assigning fields in a single constructor parameter.
Quick Quiz
1. Which access modifier makes a member accessible only within its declaring class?
2. When can a readonly field be assigned?
Was this lesson helpful?