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;
}
}
✅ 正しい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で開く
オプション
このルールは構成できません。
使用しない場合
メソッドチェーンや明示的な戻り値を使用しない場合は、このルールを安全にオフにできます。