Inheritance lets an object use features defined elsewhere instead of defining them again. In JavaScript, an object can inherit properties and methods through its prototype chain: when an object has no `toString` method of its own, the runtime can find one on its prototype. Class syntax builds on that prototype system. section 4.2 section 4.2.7
A subclass declares its superclass with `extends`. Its constructor calls `super(...)` to initialize superclass properties before using `this`. A subclass can add methods, override a method, or call the superclass version with `super.method()`. TypeScript requires the superclass constructor call. section 4.2.7 section 11.3.7
Listing 4.12 Extending a class in the index.js file in the primer folder
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
toString() {
return `toString: Name: ${this.name}, Price: ${this.price}`;
}
}
class TaxedProduct extends Product {
constructor(name, price, taxRate = 1.2) {
super(name, price);
this.taxRate = taxRate;
}
getPriceIncTax() {
return Number(this.price) * this.taxRate;
}
toString() {
let chainResult = super.toString();
return `${chainResult}, Tax: ${this.getPriceIncTax()}`;
}
}
let hat = new TaxedProduct("Hat", 100);
let boots = new TaxedProduct("Boots", 100, 1.3);
console.log(hat.toString());
console.log(boots.toString());
The `TaxedProduct` listing shows the complete JavaScript pattern: extend `Product`, initialize it with `super`, add a tax calculation, and reuse its `toString` method. section 4.2.7
Give different subclasses a common array type
In `src/index.ts`, `Employee`, `Customer`, and `Supplier` can each extend `Person`. Write `let data: Person[] = [new Employee(...), new Customer(...)];` if the array should also accept a `Supplier`. Without that annotation, an array initially containing only an employee and a customer can be inferred as `(Employee | Customer)[]`; their shared superclass does not automatically become the intended array type. section 11.3.7
TypeScript also pays attention to object shapes, not just class hierarchies. `extends` has two related-looking but distinct uses: an interface can extend another interface to require its features, while `T extends { name: string }` constrains which types a generic class accepts. Neither use is a subclass constructor call. section 11.3.7 section 11.4.2 section 12.3.3


















