Web Analytics

Inheritance

Intermediate~22 min

Inheritance allows classes to inherit properties and methods from parent classes, promoting code reuse and establishing hierarchies.

TypeScript Inheritance

Basic Inheritance

Output
Click Run to execute your code
Key Concepts:
  • extends - Creates inheritance relationship
  • super() - Calls parent constructor
  • Child inherits ALL parent members
  • Can override parent methods

Method Overriding

Child classes can override parent methods to provide specific behavior:

class Animal {
    makeSound(): void {
        console.log("Generic sound");
    }
}

class Cat extends Animal {
    makeSound(): void {  // Override
        console.log("Meow!");
    }
}

let cat = new Cat();
cat.makeSound();  // "Meow!"

Common Mistakes

1. Forgetting super() in Constructor

class Animal {
    constructor(public nameAnimal: string) {}
}

class Dog extends Animal {
    constructor(nameAnimal: string, public breed: string) {
        // โœ— Error - must call super() first!
        this.breed = breed;
    }
}

// โœ“ Correct
class Dog extends Animal {
    constructor(nameAnimal: string, public breed: string) {
        super(nameAnimal);  // Call parent first
        this.breed = breed;
    }
}

2. Accessing Private Parent Members

class Parent {
    private secret = "hidden";
}

class Child extends Parent {
    reveal() {
        console.log(this.secret);  // โœ— Error! Private
    }
}

// โœ“ Use protected instead
class Parent {
    protected secret = "hidden";
}
Best Practice: Favor composition over deep inheritance hierarchies. Keep hierarchies shallow (2-3 levels max).

Summary

  • Use extends for inheritance
  • Call super() in child constructor
  • Child inherits all parent members
  • Override methods for specific behavior
  • Use protected for inheritance-friendly members