Sub topic 3
Inheritance with `extends` and `super`
Prerequisites: basic TypeScript types, JavaScript classes, functions, this, and the idea of object-oriented programming.
Inheritance and protected members
Inheritance lets one class reuse and specialize another class. extends creates the relationship. super() calls the parent constructor, and super.method() calls a parent method.
A protected member is available inside its class and its subclasses, but not through ordinary outside code.
interface Payable {
totalPay(): number;
}
abstract class Employee implements Payable {
#employeeCode: string;
constructor(
public name: string,
protected salary: number,
employeeCode: string
) {
this.#employeeCode = employeeCode;
}
protected bonus(): number {
return this.salary * 0.1;
}
abstract totalPay(): number;
}
class Manager extends Employee {
constructor(
name: string,
salary: number,
employeeCode: string,
private reports: number
) {
super(name, salary, employeeCode);
}
protected override bonus(): number {
return super.bonus() + this.reports * 1000;
}
totalPay(): number {
return this.salary + this.bonus();
}
}
const manager = new Manager("Ada", 100_000, "m-1", 2);
console.log(manager.totalPay()); // 112000
// manager.salary; // Error: protected
// manager.bonus(); // Error: protectedThe override keyword tells TypeScript that Manager.bonus must replace a method inherited from Employee. It catches spelling mistakes and accidental overrides. Use it when overriding inherited behavior.
Abstract classes and interfaces
An abstract class can contain shared state and implemented methods, but it cannot be instantiated directly. An abstract method has no body. Each concrete subclass must implement it.
An interface describes a required shape. implements checks that a class provides the interface's members. It does not create inheritance or runtime behavior. A class can implement multiple interfaces.
The example uses both: Employee requires totalPay, and Manager supplies it.
`private` versus `#private`
TypeScript's private modifier protects access during type checking. The emitted JavaScript can still contain an ordinary property, so runtime code can bypass it with an unsafe cast such as (object as any).field.
ECMAScript #private fields are enforced by JavaScript at runtime. Code outside the class cannot read them, even with a type assertion. Choose #private when runtime privacy matters.
Privacy and type compatibility
TypeScript usually uses structural typing: objects are compatible when their public members match. Private and protected members add nominal behavior. Two classes with separately declared private fields are incompatible, even if the fields have identical names and types. Protected members also require a compatible declaration in the same class hierarchy.
Exercise
Why can Manager access salary while code using a Manager object cannot?
Show answer
salary is protected, so the class and its subclasses can use it, but outside code cannot access it directly.