prefer-return-this-type
強制執行,僅返回
this
類型,才使用this
。
🔒
擴充 「外掛:@typescript-eslint/」strict-type-checked"
在 ESLint 設定檔 中啟用此規則。
🔧
若要自動修正此規則回報的一些問題,請使用 --fix
ESLint 指令列選項.
💭
此規則需要 類型資訊 來執行。
方法串接 是 OOP 語言中的常見模式,而 TypeScript 提供了一種特殊的 多型 this
類型 來簡化它。明確宣告類別名稱回傳類型,而非 this
的類別方法會讓擴充類別難以呼叫該方法:傳回的物件會被建構為基底類別,而非衍生類別。
如果類別方法宣告的回傳類型為該類別名稱而非 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;
}
}
在 Playground 中開啟class Foo {
f1(): this {
return this;
}
f2() {
return this;
}
f3 = (): this => {
return this;
};
f4 = () => {
return this;
};
}
class Base {}
class Derived extends Base {
f(): Base {
return this;
}
}
在 Playground 中開啟選項
此規則不可組態。
不建議使用時
如果您不使用方法串接或明確的回傳值,則可以安全關閉此規則。
類型檢查的縮放規則比傳統的縮放規則強大,但您也需要設定類型檢查縮放。如果您在啟用類型檢查規則後遇到效能下降的問題,請參閱效能疑難排解。