Skip to main content

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

  1. Use access modifiers to control encapsulation
  2. Keep classes focused and single-purpose
  3. Prefer composition over inheritance
  4. Use parameter properties for simpler constructors
  5. Document public APIs with JSDoc comments

Practice Exercise

Create a Library class that manages a collection of books. Include:

  1. Methods to add and remove books
  2. A way to search for books
  3. Different access levels for properties
  4. Implementation of an interface