Classes & Object-Oriented Programming

TypeScript enhances ES6 classes with access control modifiers, shorthand constructor properties, and abstract base classes.

1. Access Modifiers (`public`, `private`, `protected`)

ModifierAccessible Inside ClassAccessible in SubclassesAccessible Outside
public (Default)YesYesYes
protectedYesYesNo
privateYesNoNo

2. Concise Parameter Properties Shorthand

Instead of declaring fields separately and assigning them inside the constructor, prefix constructor parameters with access modifiers to auto-create fields!

Verbose Standard Class:
class User {
  public name: string;
  private secretKey: string;

  constructor(name: string, key: string) {
    this.name = name;
    this.secretKey = key;
  }
}
Concise Parameter Properties:
class User {
  // Auto-declares & initializes fields!
  constructor(
    public name: string,
    private secretKey: string
  ) {}
}

3. Abstract Classes (`abstract`)

Abstract classes cannot be instantiated directly with new. They serve as base blueprints for derived child classes:

abstract class PaymentProcessor {
  constructor(public amount: number) {}

  // Abstract method must be implemented by child classes!
  abstract processPayment(): void;
}

class StripeProcessor extends PaymentProcessor {
  processPayment() {
    console.log(`Processing $${this.amount} via Stripe API...`);
  }
}

Next Up

Master Generics in TypeScript: generic functions, generic interfaces, and reusable components.

Next Lesson: Generics Basics →