Typed Method Chaining with this
What you'll learn: How to use polymorphic this types to build fluent interfaces that preserve correct type information throughout method chains.
Method chaining—calling multiple methods in sequence on the same object—creates elegant, readable APIs. But in TypeScript, a naive approach loses type information when subclasses extend your chainable class.
The Problem Without this
Imagine a QueryBuilder base class with methods that return the instance. If you type these methods to return QueryBuilder, any subclass methods won't be visible after chaining:
class QueryBuilder {
where(condition: string): QueryBuilder {
// ... add condition
return this;
}
}
class UserQueryBuilder extends QueryBuilder {
whereAdmin(): UserQueryBuilder {
// ... filter by admin
return this;
}
}
const query = new UserQueryBuilder()
.where("active")
.whereAdmin(); // Error! QueryBuilder doesn't have whereAdmin
The where() method returns QueryBuilder, not UserQueryBuilder, breaking the chain.
Using Polymorphic this
By returning this as the type, TypeScript keeps track of the actual runtime class:
class QueryBuilder {
where(condition: string): this {
// ... add condition
return this;
}
}
class UserQueryBuilder extends QueryBuilder {
whereAdmin(): this {
// ... filter by admin
return this;
}
}
const query = new UserQueryBuilder()
.where("active") // returns UserQueryBuilder
.whereAdmin(); // now accessible!
Now where() returns this, which TypeScript understands is UserQueryBuilder when called on that subclass. The chain preserves full type information.
Real-World Fluent Interfaces
This pattern shines in builder APIs, ORMs, and configuration objects where you want each method to enhance the object while maintaining all capabilities:
class HttpRequestBuilder {
withHeader(key: string, value: string): this {
return this;
}
withTimeout(ms: number): this {
return this;
}
}
class AuthenticatedRequestBuilder extends HttpRequestBuilder {
withToken(token: string): this {
return this;
}
}
const request = new AuthenticatedRequestBuilder()
.withHeader("Accept", "application/json")
.withToken("abc123")
.withTimeout(5000); // All methods available throughout
Key Takeaway: Using this as a return type enables type-safe method chaining that works correctly with inheritance, preserving the full interface of derived classes throughout the chain.