WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

TypeScript · Advanced · question 51 of 100

How can you implement an abstract class in TypeScript?

📕 Buy this interview preparation book: 100 TypeScript questions & answers — PDF + EPUB for $5

In TypeScript, an abstract class is a class that cannot be instantiated directly, but can be used as a base class for other classes. Abstract classes can have abstract methods, which are declared without an implementation, and they must be implemented by derived classes. Abstract class is defined using the ‘abstract‘ keyword.

Here’s an example of how to implement an abstract class in TypeScript:

1. Create an abstract class:

abstract class Shape {
  protected x: number;
  protected y: number;

  constructor(x: number, y: number) {
    this.x = x;
    this.y = y;
  }

  abstract getArea(): number;
  abstract getPerimeter(): number;
}

In this example, we have an abstract class ‘Shape‘ with two abstract methods, ‘getArea()‘ and ‘getPerimeter()‘. The class also has a constructor that takes two arguments, ‘x‘ and ‘y‘.

2. Define a derived class:

Now, let’s define a class ‘Rectangle‘ that derives from the abstract class ‘Shape‘ and implements the required abstract methods:

class Rectangle extends Shape {
  private width: number;
  private height: number;

  constructor(x: number, y: number, width: number, height: number) {
    super(x, y);
    this.width = width;
    this.height = height;
  }

  // Implement the abstract methods from the base class
  getArea(): number {
    return this.width * this.height;
  }

  getPerimeter(): number {
    return 2 * (this.width + this.height);
  }
}

In this example, we extend the base class ‘Shape‘, implement the required abstract methods ‘getArea()‘ and ‘getPerimeter()‘ and provide our own private properties (‘width‘ and ‘height‘) and constructor.

3. Instantiate the derived class and use the implemented methods:

Finally, we can create an object of the derived class ‘Rectangle‘ and use its methods:

const myRectangle = new Rectangle(0, 0, 5, 8);
console.log(`Area: ${myRectangle.getArea()}`);
console.log(`Perimeter: ${myRectangle.getPerimeter()}`);

Here, we create a ‘Rectangle‘ with ‘x‘, ‘y‘, ‘width‘, and ‘height‘ as ‘0‘, ‘0‘, ‘5‘, and ‘8‘, respectively. Then, we call the ‘getArea()‘ and ‘getPerimeter()‘ methods to calculate and print the area and perimeter of the rectangle.

In this way, abstract classes can be implemented in TypeScript.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic TypeScript interview — then scores it.
📞 Practice TypeScript — free 15 min
📕 Buy this interview preparation book: 100 TypeScript questions & answers — PDF + EPUB for $5

All 100 TypeScript questions · All topics