Skip to main content

prefer-return-this-type

Enforce that this is used when only this type is returned.

🔒

Extending "plugin:@typescript-eslint/strict" in an ESLint configuration enables this rule.

🔧

Some problems reported by this rule are automatically fixable by the --fix ESLint command line option.

💭

This rule requires type information to run.

Method chaining is a common pattern in OOP languages and TypeScript provides a special polymorphic this type to facilitate it. 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 when a class method declares a return type of that class name instead of this.

class Animal {
eat(): Animal {
// ~~~~~~
// Either removing this type annotation or replacing
// it with `this` would remove the type error below.
console.log("I'm moving!");
return this;
}
}

class Cat extends Animal {
meow(): Cat {
console.log('Meow~');
return this;
}
}

const cat = new Cat();
cat.eat().meow();
// ~~~~
// Error: Property 'meow' does not exist on type 'Animal'.
// because `eat` returns `Animal` and not all animals meow.
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/prefer-return-this-type": "warn"
}
};

Examples

class Foo {
f1(): Foo {
return this;
}
f2 = (): Foo => {
return this;
};
f3(): Foo | undefined {
return Math.random() > 0.5 ? this : undefined;
}
}

Options

This rule is not configurable.

When Not To Use It

If you don't use method chaining or explicit return values, you can safely turn this rule off.

Resources