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
Mark properties as readonly to prevent reassignment after initialisation:
class Config {
readonly apiUrl: string;
readonly timeout: number;
constructor(apiUrl: string, timeout: number) {
this.apiUrl = apiUrl;
this.timeout = timeout;
}
}
const config = new Config('https://api.example.com', 5000);
// config.apiUrl = 'other'; // Error: Cannot assign to 'apiUrl' because it is a read-only property
TypeScript's parameter properties shorthand lets you declare and initialise class members directly in the constructor:
class User {
constructor(
public readonly id: number,
public name: string,
private email: string,
protected role: string = 'viewer',
) {}
getEmail(): string {
return this.email;
}
}
const user = new User(1, 'Alice', 'alice@example.com');
console.log(user.id); // 1
console.log(user.name); // 'Alice'
This is equivalent to declaring each property, then assigning it in the constructor body — but significantly more concise.
Abstract classes cannot be instantiated directly. They serve as base classes that define a contract for subclasses:
abstract class Shape {
abstract area(): number;
abstract perimeter(): number;
describe(): string {
return `This shape has an area of ${this.area().toFixed(2)} and a perimeter of ${this.perimeter().toFixed(2)}`;
}
}
class Circle extends Shape {
constructor(private radius: number) {
super();
}
Subscribe to continue reading
Get full access to this lesson and all 12 lessons in this course.