A fluent interface designates an object-oriented API relying on method chaining to improve code readability. In such interfaces, methods return the
object this
to allow the caller to chain multiple method invocations.
class RichText {
constructor(private readonly text: string) {}
bold(): RichText {
// [...]
return this;
}
italic(): RichText {
// [...]
return this;
}
}
const richText = new RichText('Hello, World!');
// Chaining methods bold() and italic().
console.log(richText.bold().italic());
To better support fluent interfaces when used with a hierarchy of classes, TypeScript provides a special type this
that refers
dynamically to the type of the current class.
Methods returning this
should thus use the corresponding special type this
instead of the class name in their
signatures.