TS Inheritance
TypeScript classes can extend a single parent. The type system tracks the relationship — subclasses are assignable wherever the parent type is expected.
Basic extension
TS
class Animal {
constructor(public name: string) {}
speak(): string { return 'some sound'; }
}
class Dog extends Animal {
speak(): string { return 'woof'; }
}
const d: Animal = new Dog('Rex'); // Dog assignable to Animal
console.log(d.speak()); // woof — polymorphism
override (4.3+)
TS
class Animal {
speak(): string { return 'some sound'; }
}
class Dog extends Animal {
override speak(): string { return 'woof'; }
// override foo() {} // ✗ error — no foo() in parent
}
With noImplicitOverride set, every override must declare itself — catches typos and renamed parent methods.
Constructors and super
TS
class Cat extends Animal {
constructor(name: string, public indoor = true) {
super(name);
}
override speak() { return `${super.speak()} (purr)`; }
}
Abstract base classes
TS
abstract class Shape {
abstract area(): number;
describe() { return `area=${this.area().toFixed(2)}`; }
}
class Circle extends Shape {
constructor(public r: number) { super(); }
area() { return Math.PI * this.r ** 2; }
}
// new Shape(); // ✗ error — abstract
instanceof narrowing
TS
function describe(a: Animal) {
if (a instanceof Dog) {
// a: Dog
} else {
// a: Animal
}
}
Type-checking inheritance
TypeScript checks that an override is compatible with the parent — parameters must be assignable to the parent's, and the return type must be assignable in the other direction.
Tip: Composition often beats inheritance. "An OrderService has a PriceCalculator" usually models reality better than "An OrderService IS-A PriceCalculator".
Example
Example
class Animal {
constructor(public name: string) {}
speak(): string { return 'some sound'; }
}
class Dog extends Animal {
override speak(): string { return 'woof'; }
}
console.log(new Dog('Rex').speak());
Try it Yourself »
Exercise
Keyword for "this method overrides the parent's".
speak() { return 'woof'; }
Eight letters.
Discussion
Loading…