Conditional Chaining with this
You'll learn: How to create builder methods that return this only when certain runtime conditions are met, enabling type-safe conditional method chains.
What This Is
So far, you've seen methods that always return this for chaining. But what if you only want to allow chaining in specific circumstances? For example, a configuration builder that moves between states, or a validator that only returns this when validation passes.
Conditional chaining means your methods selectively return this based on runtime logic, while TypeScript still tracks the type correctly.
The Core Pattern
The key insight: you can return this from within conditional branches, and TypeScript will understand that only those code paths support chaining.
class FormBuilder {
private isValid = true;
addField(name: string): this {
console.log(`Adding ${name}`);
return this;
}
validate(condition: boolean): this | undefined {
if (!condition) {
this.isValid = false;
return undefined; // Break the chain
}
return this; // Allow chaining to continue
}
build(): void {
if (this.isValid) {
console.log("Form built successfully");
}
}
}
const form = new FormBuilder()
.addField("email")
.validate(true) // Returns this
?.addField("password"); // Optional chaining needed!
Notice the return type: this | undefined. When validation fails, chaining stops. The ?. operator handles the potential undefined.
Why This Matters
This pattern lets you enforce state machines or validation flows at the type level. A method can say "I only return the builder if we're in a valid state" — and TypeScript ensures callers handle the possibility of failure.
class Transaction {
private amount = 0;
setAmount(value: number): this | undefined {
if (value < 0) {
return undefined; // Invalid amount breaks chain
}
this.amount = value;
return this;
}
confirm(): void {
console.log(`Confirmed: $${this.amount}`);
}
}
const result = new Transaction()
.setAmount(100)
?.confirm(); // Must use ?. because setAmount might return undefined
Key Takeaway: By returning this | undefined (or other union types), methods can conditionally support chaining based on runtime logic, and TypeScript enforces safe handling of broken chains with optional chaining operators.