Classes in TypeScript
TypeScript adds type-safety and additional features to JavaScript classes, making object-oriented programming more robust and predictable.
Basic Class Structure
class User {
// Properties with type annotations
name: string;
email: string;
private loginCount: number;
constructor(name: string, email: string) {
this.name = name;
this.email = email;
this.loginCount = 0;
}
// Method with return type
getInfo(): string {
return `${this.name} (${this.email})`;
}
}
const user = new User("Alice", "alice@example.com");
Access Modifiers
TypeScript provides three access modifiers:
class BankAccount {
public accountHolder: string; // Accessible everywhere
private balance: number; // Only inside the class
protected accountNumber: string; // Inside class and subclasses
constructor(holder: string, initialBalance: number) {
this.accountHolder = holder;
this.balance = initialBalance;
this.accountNumber = Math.random().toString();
}
}
Parameter Properties
A shorthand way to define and initialize class members:
class Point {
// Automatically creates and initializes x and y properties
constructor(
public x: number,
public y: number
) {}
getDistance(): number {
return Math.sqrt(this.x ** 2 + this.y ** 2);
}
}
Inheritance
Classes can extend other classes:
class Animal {
constructor(protected name: string) {}
makeSound(): void {
console.log("Some sound");
}
}
class Dog extends Animal {
constructor(name: string, private breed: string) {
super(name);
}
makeSound(): void {
console.log("Woof!");
}
getInfo(): string {
return `${this.name} is a ${this.breed}`;
}
}
Implementing Interfaces
Classes can implement interfaces to ensure they have required properties and methods:
interface Vehicle {
start(): void;
stop(): void;
speed: number;
}
class Car implements Vehicle {
speed: number = 0;
start(): void {
console.log("Engine started");
}
stop(): void {
this.speed = 0;
console.log("Car stopped");
}
}
Best Practices
- Use access modifiers to control encapsulation
- Keep classes focused and single-purpose
- Prefer composition over inheritance
- Use parameter properties for simpler constructors
- Document public APIs with JSDoc comments
Practice Exercise
Create a Library class that manages a collection of books. Include:
- Methods to add and remove books
- A way to search for books
- Different access levels for properties
- Implementation of an interface