Classes and Object-Oriented Programming
TypeScript brings full support for object-oriented programming patterns, including classes, inheritance, access modifiers, and abstract classes.
1. Access Modifiers
TypeScript provides three access modifiers to control the visibility of class properties and methods.
- public (Default): Properties and methods are accessible from anywhere.
- private: Properties and methods are only accessible within the class they are declared.
- protected: Properties and methods are accessible within the class and its subclasses.
class BankAccount {
public owner: string;
private balance: number;
constructor(owner: string, initialBalance: number) {
this.owner = owner;
this.balance = initialBalance;
}
public getBalance(): number {
return this.balance;
}
}2. Parameter Properties
You can simplify class declarations by defining access modifiers directly within the constructor parameters. TypeScript automatically converts them into properties.
Shorthand Syntax
class UserProfile {
// TypeScript automatically creates and initializes 'username' and 'email'
constructor(public username: string, private email: string) {}
}This replaces the need to declare fields separately and assign them in the constructor body.
3. Implementing Interfaces
Classes can implement interfaces to enforce specific contracts. A class must implement all properties and methods defined in the interface.
interface Logger {
log: (message: string) => void;
}
class ConsoleLogger implements Logger {
public log(message: string): void {
console.log(message);
}
}4. Abstract Classes
Abstract classes act as base classes that cannot be instantiated directly. They can contain implemented methods as well as abstract methods (which subclasses must implement).
abstract class DatabaseConnector {
// Concrete method
public disconnect(): void {
console.log("Disconnected from database.");
}
// Abstract method (must be implemented by subclasses)
abstract connect(): void;
}
class PostgresConnector extends DatabaseConnector {
public connect(): void {
console.log("Connected to Postgres.");
}
}5. Summary
- Access modifiers (
public,private,protected) control visibility of class members. - Parameter properties in constructors act as a shorthand to declare and initialize fields.
- Classes use
implementsto conform to interface structures. - Abstract classes define template structures and methods for inheritance.