You are viewing a free preview of this lesson.
Subscribe to unlock all 12 lessons in this course and every other course on LearningBro.
TypeScript enhances JavaScript's class syntax with access modifiers, abstract classes, interfaces, and other object-oriented features. Whilst TypeScript supports multiple paradigms, understanding OOP concepts is essential for working with many libraries and frameworks.
A TypeScript class looks similar to a JavaScript class, with the addition of type annotations:
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet(): string {
return `Hello, I'm ${this.name} and I'm ${this.age} years old.`;
}
}
const alice = new Person('Alice', 30);
console.log(alice.greet());
TypeScript provides three access modifiers that control visibility:
class BankAccount {
public owner: string; // accessible anywhere (default)
protected accountType: string; // accessible in this class and subclasses
private balance: number; // accessible only in this class
constructor(owner: string, initialBalance: number) {
this.owner = owner;
this.accountType = 'current';
this.balance = initialBalance;
}
public deposit(amount: number): void {
this.balance += amount;
}
public getBalance(): number {
return this.balance;
}
}
const account = new BankAccount('Alice', 1000);
account.deposit(500);
console.log(account.getBalance()); // 1500
// account.balance; // Error: Property 'balance' is private
Subscribe to continue reading
Get full access to this lesson and all 12 lessons in this course.