returnThisTypes
Enforce that
thisis used when onlythistype is returned.
✅ This rule is included in the ts logical presets.
Method chaining is a pattern in object-oriented programming where class methods return the instance of the class being called.
TypeScript provides a special polymorphic this type to facilitate method chaining.
When a base class method returns this, calling that method on any sub-classes will be known to return the specific sub-class, rather than the general base class.
Class methods that explicitly declare a return type of the class name instead of this make it harder for extending classes to call that method: the returned object will be typed as the base class, not the derived class.
This rule reports on class methods that declare their return type as that specific class name rather rather than this.
Examples
Section titled “Examples”class Builder { setValue(): Builder { return this; }}class Builder { setValue = (): Builder => this;}class Builder { get self(): Builder { return this; }}class Animal<T> { eat(): Animal<T> { return this; }}class Builder { setValue(): this { return this; }}class Builder { setValue = (): this => this;}class Builder { get self(): this { return this; }}class Builder { clone(): Builder { return new Builder(); }}class Builder { setValue() { return this; }}Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”If you intentionally want to restrict method chaining to the exact class type and prevent subclasses from inheriting the fluent interface, this rule might not be for you. You might consider using Flint disable comments and/or configuration file disables for specific cases instead of completely disabling this rule.