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.
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/prefer-return-this-type": "error"
}
};
在线运行试试这个规则 ↗

示例

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

何时不使用它

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

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

选项

该规则不可配置。

资源