Hello! In our last lesson, we saw how to enforce architectural constraints by using new.target to create abstract base classes. This pattern allows us to define a blueprint that must be extended but cannot be instantiated directly, which is a powerful tool for building frameworks.
Today, we'll shift our focus from controlling how classes are inherited to improving how class instances are used. Our goal is to implement a fluent interface (method chaining) on a custom class. This pattern makes APIs more readable and expressive by allowing you to chain method calls together in a natural, flowing sequence. You have likely encountered this already when using built-in array methods.

By the end of this lesson, you'll be able to build your own classes that support this elegant and powerful interaction style.
What is a Fluent Interface?
A fluent interface is a design pattern for object-oriented APIs where the result of each method call is the object instance itself, allowing calls to be chained together. This creates code that can be read almost like a sentence, often described as a Domain-Specific Language (DSL).
To get a feel for common examples and the overall goal, let's watch a short introductory clip.
Building Fluent Interfaces in TypeScript
The video 'Building Fluent Interfaces in TypeScript' by Andrew Burgess starts by showcasing familiar examples of fluent interfaces, such as jQuery and testing assertion libraries. This will help ground the concept in patterns you may have seen before.
Watch from 00:15 to 01:01. The key idea to grasp is how chaining method calls creates a more descriptive and readable API.
The primary benefits of this pattern are improved code readability and a reduction in the need for intermediate variables to store state between operations.
The Core Mechanism: return this
The secret to enabling method chaining is surprisingly simple: each method that you want to be part of the chain must end by returning the current object instance, which is referenced by the this keyword.
Let's look at a straightforward implementation of this principle.
Fluent APIs with Function Chaining
The article 'Mastering JavaScript Function Chaining' provides a clear, practical example of a custom class with a fluent API. This will show you the pattern in its most direct form.
Read the section '5.2. Fluent APIs with Function Chaining'. Pay close attention to the Drawing class. Notice how the circle(), square(), and rectangle() methods all end with return this;. The render() method, however, does not, making it a 'terminal' method that ends the chain.
As you saw in the Drawing example, the methods for adding shapes are chainable because they return the Drawing instance. The render() method performs a final action and doesn't return this, effectively ending the chain.
Let's build our own simple example to solidify this. We'll create a Calculator class.
class Calculator {
constructor(initialValue = 0) {
this.value = initialValue;
}
add(number) {
this.value += number;
// By returning 'this', we return the Calculator instance itself,
// making it available for the next method call.
return this;
}
subtract(number) {
this.value -= number;
return this;
}
multiply(number) {
this.value *= number;
return this;
}
// This is a 'terminal' method. It doesn't return 'this'.
// It returns the final computed value, so no more methods can be chained after it.
getResult() {
return this.value;
}
}
// Let's use it!
const result = new Calculator(10) // starts with 10
.add(5) // instance value becomes 15
.subtract(3) // instance value becomes 12
.multiply(2) // instance value becomes 24
.getResult(); // returns the final value, 24
console.log(result); // Output: 24
Each call to add, subtract, or multiply modifies the internal value property and then passes the same object instance along for the next call.
A Practical Application: The Builder Pattern
One of the most common and powerful use cases for a fluent interface is the Builder design pattern. You may recall this pattern from your computer science studies; its purpose is to separate the construction of a complex object from its representation. A fluent interface makes implementing a builder incredibly intuitive.
A query builder is a classic example that should resonate with your experience in database development. Let's see how one is built.
Building Fluent Interfaces in TypeScript
This next segment from the same video demonstrates building a simple SQL query builder. This is a perfect real-world application of the fluent interface.
Watch from 01:01 to 03:51. Notice how the select, from, and where methods each modify a piece of the object's internal state and then return this. The build method is the terminal method that assembles the final string from the collected state.
The QueryBuilder class accumulates pieces of the final SQL query (fields, table, wheres) in its properties with each method call. The final build() call consumes this internal state to produce the final output string. This step-by-step construction is the essence of the Builder pattern.
Test your understanding!
Your task is to implement a fluent StringBuilder class. It should allow for appending, prepending, and wrapping strings.
- Create a class
StringBuilderthat is initialized with an optional initial string. - Implement an
append(str)method that adds a string to the end. - Implement a
prepend(str)method that adds a string to the beginning. - Implement a
wrap(prefix, suffix)method that adds a prefix and a suffix to the current string. - Implement a
toString()terminal method that returns the final string.
All methods except toString() should be chainable.
Example usage:new StringBuilder('World').prepend('Hello, ').append('!').wrap('(', ')').toString() should produce '(Hello, World!)'.
Show answer
Here's one way to implement the StringBuilder:
class StringBuilder {
constructor(initialStr = "") {
this.str = initialStr;
}
append(str) {
this.str = this.str + str;
return this;
}
prepend(str) {
this.str = str + this.str;
return this;
}
wrap(prefix, suffix) {
this.str = prefix + this.str + suffix;
return this;
}
toString() {
return this.str;
}
}
// Testing the implementation
const myString = new StringBuilder('World')
.prepend('Hello, ')
.append('!')
.wrap('(', ')')
.toString();
console.log(myString); // Output: (Hello, World!)
Conclusion
You've now learned how to implement one of the most common and user-friendly API design patterns in JavaScript. By making your methods return the object instance, you can create expressive, readable, and powerful interfaces for your classes.
Key Takeaways:
- A fluent interface (or method chaining) is a pattern where methods are called sequentially on the same object instance.
- The core mechanism is having each chainable method
return this. - Terminal methods are used at the end of a chain to return a final value or perform a concluding action, breaking the chain.
- The Builder pattern is a classic design pattern for constructing complex objects step-by-step, and it is frequently implemented using a fluent interface.
One final point to consider is that this pattern relies on methods that mutate the object's internal state. These are examples of side effects, a concept we will explore in great detail in our next module.
Next Up
This lesson concludes our module on compositional patterns. We've explored mixins, traits, abstract classes, and now fluent interfaces—all powerful tools for structuring your object-oriented code.
In the next module, we will pivot to a different paradigm: Functional Programming. Our first lesson will be to differentiate between pure and impure functions by identifying side effects. This will provide a foundational understanding for building more predictable and maintainable code by controlling state and side effects, offering a powerful contrast to the stateful, mutable objects we've often worked with so far.