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.
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.
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());Area: 16Square must implement area() because Shape declares it as abstract.
abstract class Animal {
abstract makeSound(): string;
}
class Cat extends Animal {
makeSound(): string {
return "Meow";
}
}
console.log(new Cat().makeSound());MeowCat 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.
