Sub topic 15
Safe Overriding and Abstract Classes
This chapter assumes you know basic TypeScript types, classes, inheritance, and the this keyword. Inheritance lets a subclass reuse and specialize a parent class. The override keyword makes that specialization safer. Abstract classes define shared behavior while requiring subclasses to complete specific parts.
Safe overriding with `override`
A subclass overrides a method when it provides a new implementation for a method declared by its base class. Mark the method with override:
class Employee {
constructor(
public readonly name: string,
protected salary: number
) {}
protected bonus(): number {
return this.salary * 0.1;
}
totalPay(): number {
return this.salary + this.bonus();
}
}
class Manager extends Employee {
constructor(
name: string,
salary: number,
private readonly reportCount: number
) {
super(name, salary);
}
protected override bonus(): number {
return super.bonus() + this.reportCount * 1000;
}
}
const manager = new Manager("Ada", 100_000, 2);
console.log(manager.totalPay()); // 112000super.bonus() calls the parent implementation. The manager then adds an amount based on the number of reports.
The compiler checks that an override member actually exists in the parent class. It also checks that the replacement is compatible with the inherited member. This catches errors such as misspelling bonus as bonuss, which would otherwise create a new method instead of replacing the old one.
You can require this check for every override with noImplicitOverride in tsconfig.json:
{
"compilerOptions": {
"strict": true,
"noImplicitOverride": true
}
}The keyword protects the relationship between the two classes. It does not prevent a subclass from changing the method's behavior.
Abstract classes and abstract members
An abstract class is a base class that cannot be instantiated directly. An abstract member declares a requirement without providing an implementation. Every concrete subclass must implement that member.
abstract class Shape {
abstract area(): number;
describe(): string {
return `Area: ${this.area().toFixed(2)}`;
}
}
class Circle extends Shape {
constructor(private readonly radius: number) {
super();
}
override area(): number {
return Math.PI * this.radius ** 2;
}
}
const circle = new Circle(2);
console.log(circle.describe()); // Area: 12.57
// const shape = new Shape(); // ErrorThe shared describe method calls area, but Shape does not need to know the formula. Each subclass supplies its own formula. Circle uses override because area fulfills the inherited abstract member.
Exercise
Why does Circle.area use both override and a concrete method body?
Show answer
Shape declares area as abstract, so Circle must implement it. override tells TypeScript that this implementation fulfills an inherited member and asks the compiler to verify that relationship.