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

The Method Chaining Pattern

Understanding how returning this enables fluent interfaces and chainable method calls in classes.

The Method Chaining Pattern

You'll learn how returning this from methods enables fluent, chainable APIs that maintain proper type information across calls.

What Is Method Chaining?

Method chaining is the pattern where you call multiple methods on the same object in sequence, like builder.setName("Alice").setAge(30).build(). This works because each method returns the object itself (this), allowing the next method to be called immediately.

In TypeScript, returning this has a special benefit: it preserves the exact type of the object, even when called on subclasses. This means your chains remain type-safe and autocomplete-friendly throughout the entire sequence.

Why this Instead of a Fixed Type?

Imagine a base class QueryBuilder. If your methods returned QueryBuilder, then any subclass like AdvancedQueryBuilder would "lose" its specific type when chaining. By returning this, TypeScript ensures the return type matches whatever class instance you're actually working with.

Think of this as a mirror that reflects back the true identity of the object, not just its parent class.

Basic Pattern Example

class FluentCalculator {
  private value = 0;

  add(n: number): this {
    this.value += n;
    return this; // Returns the exact instance
  }

  multiply(n: number): this {
    this.value *= n;
    return this;
  }

  getResult(): number {
    return this.value;
  }
}

const result = new FluentCalculator()
  .add(5)
  .multiply(3)
  .add(2)
  .getResult(); // 17

Each add() and multiply() returns this, so you can keep calling methods in a readable, left-to-right flow.

With Inheritance

class ExtendedCalculator extends FluentCalculator {
  subtract(n: number): this {
    // Subclass method
    return this;
  }
}

const extended = new ExtendedCalculator()
  .add(10)
  .subtract(3) // Available because 'this' preserves ExtendedCalculator
  .multiply(2)
  .getResult(); // 14

Without polymorphic this, calling .add(10) would return type FluentCalculator, and .subtract(3) wouldn't exist on that type.

When to Use This Pattern

Method chaining shines when you're configuring objects step-by-step: builders, query constructors, configuration objects, or any API where multiple small tweaks are common. It reads like natural language and keeps related operations grouped together.

Key Takeaway: Returning this from methods creates fluent, type-safe method chains that preserve the exact class type through inheritance, enabling powerful builder and configuration patterns.