What it is and why to use it
A method returning the polymorphic this type preserves the more specific receiver type in a chain. This is useful for builders where a base method should not erase subclass methods. Returning this also makes it clear that the method continues working on the same object.
Common mistakes and limitations
Fluent syntax does not imply immutability: this example mutates its receiver. Detached methods can also lose the intended runtime this binding. Document whether a builder returns the same instance or creates a new one.
Run this example
Use TypeScript 5.8 or later with strict checking and an ES2022 target. Save each complete example independently as example.ts, compile it, then run the generated JavaScript with a compatible Node.js installation. Compiler-only options below affect checking; they do not add runtime validation.
Terminal — compile and run
npx tsc example.ts --strict --target ES2022 --module commonjs
node example.jsSyntax
setName(name: string): this { return this; }Examples
Fluent Methods with the this Type
Standalone TypeScript 5.8+ example; expected output is explained below.
class Counter {
protected value = 0;
add(amount: number): this { this.value += amount; return this; }
}
class DisplayCounter extends Counter {
show(): string { return "Total: " + this.value; }
}
console.log(new DisplayCounter().add(2).add(3).show());- add changes the protected numeric state and returns the receiver.
- The receiver is a DisplayCounter, so the chain retains access to show.
- The two additions build a total of 5. Returning the base Counter type instead would lose the subclass-specific method in the chain’s static type.
- Expected output: Total: 5
Best practices
- Fluent syntax does not imply immutability: this example mutates its receiver. Detached methods can also lose the intended runtime this binding. Document whether a builder returns the same instance or creates a new one.
- Keep external-input validation separate from compile-time type descriptions.
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook