メインコンテンツにスキップ

prefer-return-this-type

this 型のみが返される場合に this が使用されることを強制します。

🔒

拡張 "plugin:@typescript-eslint/strict-type-checked" ESLint構成 で有効にすると、このルールが有効になります。

🔧

このルールによって報告された一部の問題は、 --fix ESLint コマンドラインオプション.

で自動的に修正できます

💭 このルールを実行するには、 型情報

が必要です。

メソッドチェーンは、OOP言語で一般的なパターンであり、TypeScriptでは、それを容易にする特別な多相性 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.
このルールは、クラスメソッドが this の代わりにそのクラス名を戻り値の型として宣言した場合に報告します。
module.exports = {
"rules": {
"@typescript-eslint/prefer-return-this-type": "error"
}
};

.eslintrc.cjs

Playgroundでこのルールを試す ↗

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

Playgroundで開く

オプション

このルールは構成できません。

使用しない場合


メソッドチェーンや明示的な戻り値を使用しない場合は、このルールを安全にオフにできます。

型チェックされたリンタールールは、従来のリンタールールよりも強力ですが、型チェックされたリンティングを設定する必要があります。型チェックされたルールを有効にした後、パフォーマンスの低下が発生した場合は、パフォーマンスのトラブルシューティングを参照してください。