Sub topic 13
Inheritance with `extends` and `super`
Assume you know basic TypeScript types, functions, objects, the this keyword, and the general idea of object-oriented programming. Inheritance lets one class reuse and specialize another class.
A class that inherits from another class is called a subclass or derived class. The class it inherits from is the base class or superclass. Use extends to create the relationship.
Extending a class
The subclass receives the base class's accessible fields and methods. Its constructor must call super(...) before it uses this. The super call runs the base constructor and initializes the inherited part of the object.
class Employee {
constructor(
public readonly name: string,
protected salary: number
) {}
describe(): string {
return `${this.name} earns ${this.salary}`;
}
}
class Manager extends Employee {
constructor(
name: string,
salary: number,
public readonly teamSize: number
) {
super(name, salary);
}
describe(): string {
return `${super.describe()} and manages ${this.teamSize} people`;
}
}
const manager = new Manager("Ada", 100000, 4);
console.log(manager.describe());
// Ada earns 100000 and manages 4 peopleManager inherits name, salary, and describe from Employee. Its constructor accepts all required data, then passes the employee data to super. The subclass adds teamSize.
Calling inherited behavior with `super`
A subclass can define a method with the same name as a base method. This is called overriding. Inside the replacement method, super.methodName() calls the base implementation.
Calling the base method is useful when the subclass needs to keep existing behavior and add to it. You can also use super to access a base constructor, but you cannot call a base class's private implementation directly.
Choosing inheritance carefully
Inheritance models an “is a” relationship. A Manager is an Employee, so an Employee variable can refer to a Manager object. Use inheritance when the subclass genuinely follows the base class's contract. If two classes only share implementation details, composition, where one object contains another object, is often easier to change.
Exercise
Why does the Manager constructor call super(name, salary) before using this.teamSize?
Show answer
The call initializes the inherited Employee state and must happen before the derived constructor accesses this.