Exploring Abstract Classes in TypeScript

Abstract Class:

An abstract class in TypeScript is a class that cannot be instantiated on its own and is designed to be sub-classed by other classes. It can contain a mix of abstract and concrete methods.

Example:

abstract class Shape {
  abstract calculateArea(): number;

  display(): void {
    console.log("Displaying shape.");
  }
}

class Circle extends Shape {
  constructor(private radius: number) {
    super();
  }

  calculateArea(): number {
    return Math.PI * this.radius ** 2;
  }
}

const myCircle = new Circle(5);
console.log(myCircle.calculateArea()); // Output: 78.54
myCircle.display(); // Output: Displaying shape.

In this example, Shape is an abstract class with an abstract method calculateArea() and a concrete method display(). The Circle class extends Shape and provides an implementation for the abstract method. An object of Circle can be instantiated and used.

Interface vs Abstract Class:

The main distinctions between interfaces and abstract classes are:

  1. Abstract Methods:

    • Abstract Class: Can include abstract methods with or without providing a base implementation.

    • Interface: Only declares the structure that implementing classes must follow without including any implementation details.

  2. Regular Methods:

    • Abstract Class: Can contain regular methods with an implementation.

    • Interface: Cannot include any method implementations.

  3. Instantiation:

    • Abstract Class: Cannot be instantiated on its own; requires extension.

    • Interface: Doesn't have a concrete existence and cannot be instantiated.

Choose between an abstract class and an interface based on the specific needs of your design. Abstract classes are more suitable when there's a need for shared implementation, while interfaces are great for defining contracts without implementation details.

Stay tuned for more TypeScript insights and best practices!