TypeScript ยท Chapter 25 of 44

TypeScript Abstract Classes

An abstract class is a class that cannot be instantiated directly; it exists to be extended by other classes. Abstract classes can define both regular methods and abstract methods that subclasses must implement.

Abstract methods have no body in the abstract class itself โ€” they only declare a signature. Every non-abstract subclass is required to provide an actual implementation for each abstract method.

Syntax
abstract class Shape {
  abstract area(): number;
}

Declaring an abstract class

You mark a class as `abstract` using the `abstract` keyword before `class`. Attempting to write `new` on an abstract class directly causes a compile-time error.

Abstract methods

An abstract method is declared with the `abstract` keyword and no body, like `abstract makeSound(): string;`. Subclasses must override it with a real implementation.

Example 1 (typescript)
abstract class Shape {
  abstract area(): number;
  describe(): string {
    return `Area: ${this.area()}`;
  }
}
class Square extends Shape {
  constructor(private side: number) {
    super();
  }
  area(): number {
    return this.side * this.side;
  }
}
console.log(new Square(4).describe());
Output
Area: 16

Square must implement area() because Shape declares it as abstract.

Example 2 (typescript)
abstract class Animal {
  abstract makeSound(): string;
}
class Cat extends Animal {
  makeSound(): string {
    return "Meow";
  }
}
console.log(new Cat().makeSound());
Output
Meow

Cat provides the required implementation of the abstract makeSound method.

Key points

  • Abstract classes cannot be instantiated directly.
  • Abstract methods declare a signature without an implementation.
  • Subclasses must implement every abstract method.
  • Abstract classes can still contain regular, fully implemented methods.
๐Ÿ’ก Note: Use abstract classes when you want to share common code between related classes while forcing certain methods to be implemented individually.

๐Ÿ“ Quick Quiz

1. Can you create an instance of an abstract class directly?

2. What must a subclass do with an abstract method?

3. Which keyword declares an abstract class?