Skip to main content

prefer-return-this-type

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

🔒

ESLint 配置 中扩展"plugin:@typescript-eslint/strict-type-checked" 可启用此规则。

🔧

此规则报告的一些问题可通过 --fix ESLint 命令行选项自动修复

💭

该规则需要 类型信息 才能运行,但这会带来性能方面的权衡。

方法链接 是 OOP 语言中的常见模式,TypeScript 提供了一个特殊的 多态性 this 来促进它。明确声明类名而不是 this 的返回类型的类方法使扩展类更难调用该方法:返回的对象将被键入为基类,而不是派生类。

¥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 或 安全地替换字符串方法。

¥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.
eslint.config.mjs
export default tseslint.config({
rules: {
"@typescript-eslint/prefer-return-this-type": "error"
}
});

在线运行试试这个规则 ↗

示例

¥Examples

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

选项

该规则不可配置。

何时不使用它

¥When Not To Use It

如果你不使用方法链接或显式返回值,则可以安全地关闭此规则。

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


Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting.

See Troubleshooting > Linting with Type Information > Performance if you experience performance degradations after enabling type checked rules.

'## 资源'