Mixing Chainable and Non-Chainable Methods
What you'll learn: How to design class APIs where some methods return this for chaining while others return meaningful values.
The Design Challenge
Not every method should be chainable. A well-designed class API mixes two types of methods:
- Chainable methods (configuration, setup) return
thisto enable fluent interfaces - Terminal methods (execution, retrieval) return actual results and end the chain
The key is using TypeScript's type system to ensure each method returns the appropriate type.
The Pattern
class QueryBuilder {
private table: string = '';
private conditions: string[] = [];
// Chainable: returns this
from(table: string): this {
this.table = table;
return this;
}
// Chainable: returns this
where(condition: string): this {
this.conditions.push(condition);
return this;
}
// Non-chainable: returns string
build(): string {
return `SELECT * FROM ${this.table} WHERE ${this.conditions.join(' AND ')}`;
}
// Non-chainable: returns number
count(): number {
return this.conditions.length;
}
}
const query = new QueryBuilder()
.from('users')
.where('age > 18')
.where('active = true')
.build(); // Returns string, chain ends here
const conditionCount = new QueryBuilder()
.from('products')
.where('price < 100')
.count(); // Returns number, chain ends here
Why Mix Both Types?
Chainable methods configure state incrementally. Terminal methods produce the final output. Trying to chain after a terminal method would be nonsensical—you've already extracted your result!
This pattern creates intuitive APIs where the return type signals intent: this means "keep building," while specific types mean "here's your answer."
Key Takeaway: Design APIs with this return types for configuration methods and specific return types for terminal operations—TypeScript will prevent invalid chaining attempts while enabling fluent builder patterns.