Advertisement
Beginner TypeScript, Classes: Access Modifiers, Abstract Classes & Implements

How do you declare and use an abstract class?

Short answer

Mark a class with the abstract keyword to prevent it from being instantiated directly with 'new' — it exists only to be extended, typically providing shared implementation plus one or more abstract methods that subclasses MUST implement.

Save TypeScript mock interview
Advertisement
AModel answer
Mark a class with the abstract keyword to prevent it from being instantiated directly with 'new' — it exists only to be extended, typically providing shared implementation plus one or more abstract methods that subclasses MUST implement.
abstract class Shape {
  abstract area(): number;
  describe(): string { return `Area: ${this.area()}`; }
}
class Circle extends Shape {
  constructor(private radius: number) { super(); }
  area() { return Math.PI * this.radius ** 2; }
}
// new Shape(); // Error: cannot instantiate an abstract class
Real-world example
Defining a base PaymentMethod class where each subclass (CreditCard, PayPal) must implement its own charge() logic.
Likely follow-ups
  • Can an abstract class have a constructor with implementation, even though it can't be instantiated directly?
Related topics