Intermediate LevelJavaScript & TypeScript
What is the override keyword and abstract classes in TypeScript?
❓ Interview Prompt: Explain abstract classes, abstract methods, and noImplicitOverride compiler flag with override keyword.
Abstract Classes (abstract class Base):
Classes that cannot be instantiated directly via new. Served as base classes for subclasses.
•
Abstract Methods: Declared without implementation; subclasses MUST implement them.
The override Keyword (override method()):
Ensures a subclass method explicitly overrides a method present in its parent class.
•
When
noImplicitOverride: true is set in tsconfig, forgetting override on overridden methods triggers a compiler error! Protects against refactoring bugs when parent methods are renamed.Code Implementation Example
typescript
abstract class Shape {
abstract getArea(): number; // Subclass must implement
printArea() {
console.log('Area:', this.getArea());
}
}
class Circle extends Shape {
constructor(public radius: number) {
super();
}
// Explicit override annotation
override getArea(): number {
return Math.PI * this.radius ** 2;
}
}
const c = new Circle(5);
c.printArea();💡Abstract base class shape definition and child class explicit method override.
🎯 Interview Key Takeaway
Abstract classes define template contracts for subclasses. Use override to ensure overridden methods stay synced with parent classes.
#TypeScript#Abstract Classes#override#Intermediate
Back to all JavaScript & TypeScript Questions→