Course contentsShow
← TypeScript
Lesson 1069 of 1,79625. The this TypeFree lesson

Inheritance and this Type Propagation

How the this type flows through inheritance hierarchies without redeclaration.

Inheritance and this Type Propagation

What you'll learn: How TypeScript's this return type automatically adapts across inherited classes without manual redeclaration.

The Magic of Automatic this Propagation

When you use this as a return type in a base class method, TypeScript doesn't lock it to that specific class. Instead, it propagates through the inheritance hierarchy automatically. Each subclass that inherits the method gets a version that returns the subclass type, not the base class type.

This means you write the method once with return this, and every class in the chain gets the correctly-typed version for free.

How It Works in Practice

class Animal {
  name: string = "";

  setName(name: string): this {
    this.name = name;
    return this;
  }
}

class Dog extends Animal {
  bark(): this {
    console.log("Woof!");
    return this;
  }
}

class Cat extends Animal {
  meow(): this {
    console.log("Meow!");
    return this;
  }
}

// TypeScript knows the exact type at each step
const dog = new Dog()
  .setName("Buddy")  // returns Dog, not Animal
  .bark();           // ✅ bark() exists on Dog

const cat = new Cat()
  .setName("Whiskers")  // returns Cat, not Animal
  .meow();              // ✅ meow() exists on Cat

Notice that setName() is defined only in Animal, yet when called on a Dog instance, it returns Dog. When called on a Cat, it returns Cat. You didn't redeclare anything—the this type adapted automatically.

No Redeclaration Needed

class Builder {
  private value: number = 0;

  add(n: number): this {
    this.value += n;
    return this;
  }
}

class AdvancedBuilder extends Builder {
  multiply(n: number): this {
    // Complex logic here
    return this;
  }
}

// Both methods return AdvancedBuilder when called on it
const result = new AdvancedBuilder()
  .add(5)        // returns AdvancedBuilder
  .multiply(2)   // returns AdvancedBuilder
  .add(3);       // still AdvancedBuilder

The add() method was written once in Builder, but it "knows" to return AdvancedBuilder when used by that subclass.

Key Takeaway: The this return type automatically flows through inheritance, giving each subclass properly typed method chaining without redundant type declarations in every child class.