Abstract Class in TypeScript

Abstract Class in TypeScript

In TypeScript, an abstract class is a class that cannot be instantiated directly. It is used as a base class to provide a common structure for its subclasses. Abstract classes can define abstract methods that must be implemented by their subclasses. Abstract classes provide a way to enforce a common structure across different classes.

Syntax of Abstract Class

The syntax to create an abstract class in TypeScript is as follows:

abstract class ClassName {
    abstract methodName(): returnType;
}

Code Example

abstract class Animal {
    abstract makeSound(): void;
}

class Dog extends Animal {
    makeSound() {
        console.log("Woof! Woof!");
    }
}

let myDog = new Dog();
myDog.makeSound();

Top FAQs with Answers

Q1. Can we create an instance of an abstract class in TypeScript?

No, we cannot create an instance of an abstract class in TypeScript.

Q2. Can an abstract class have non-abstract methods?

Yes, an abstract class can have non-abstract methods, and they can be called by its subclasses.

Q3. Can an abstract class be extended by multiple classes?

Yes, an abstract class can be extended by multiple classes.

Q4. Can we declare an abstract class with a constructor?

Yes, we can declare an abstract class with a constructor.

Q5. Can a subclass of an abstract class be abstract?

Yes, a subclass of an abstract class can be abstract, and it must implement all the abstract methods of its parent class.

 

Conclusion

Abstract classes in TypeScript provide a way to create a common structure for related classes while enforcing the implementation of certain methods. They cannot be instantiated directly and must be extended by subclasses that implement their abstract methods. Abstract classes allow for better code organization and reduce code duplication. With the help of TypeScript’s abstract class feature, developers can enforce a consistent structure and design across their codebase, leading to better maintainability and readability.