unbound-method
バインドされていないメソッドが、期待されるスコープで呼び出されるように強制します。
拡張 "plugin:@typescript-eslint/recommended-type-checked"
を ESLint設定 で有効にすると、このルールが有効になります。
このルールを実行するには 型情報 が必要です。
クラスメソッド関数は、スタンドアロン変数として渡されるとクラススコープを保持しません(「バインドされていない」)。関数が`this`にアクセスしない場合は、`this: void`で注釈を付けるか、代わりにアロー関数を使用することを検討してください。それ以外の場合は、クラスメソッドを値として渡すと、`this`をキャプチャできず、型安全性が失われる可能性があります。
このルールは、クラスメソッドがバインドされていない方法で参照されている場合に報告します。
Jestを使用している場合は、eslint-plugin-jest
のバージョンのこのルールを使用してテストファイルをlintできます。これは、`expect`呼び出しにバインドされていないメソッドを渡すことが許容される場合を認識しています。
module.exports = {
"rules": {
"@typescript-eslint/unbound-method": "error"
}
};
このルールをPlaygroundでお試しください ↗
例
- ❌ 正しくない
- ✅ 正しい
class MyClass {
public log(): void {
console.log(this);
}
}
const instance = new MyClass();
// This logs the global scope (`window`/`global`), not the class instance
const myLog = instance.log;
myLog();
// This log might later be called with an incorrect scope
const { log } = instance;
// arith.double may refer to `this` internally
const arith = {
double(x: number): number {
return x * 2;
},
};
const { double } = arith;
Playgroundで開くclass MyClass {
public logUnbound(): void {
console.log(this);
}
public logBound = () => console.log(this);
}
const instance = new MyClass();
// logBound will always be bound with the correct scope
const { logBound } = instance;
logBound();
// .bind and lambdas will also add a correct scope
const dotBindLog = instance.logUnbound.bind(instance);
const innerLog = () => instance.logUnbound();
// arith.double explicitly declares that it does not refer to `this` internally
const arith = {
double(this: void, x: number): number {
return x * 2;
},
};
const { double } = arith;
Playgroundで開くオプション
このルールは、次のオプションを受け入れます
type Options = [
{
/** Whether to skip checking whether `static` methods are correctly bound. */
ignoreStatic?: boolean;
},
];
const defaultOptions: Options = [{ ignoreStatic: false }];
ignoreStatic
`{ ignoreStatic: true }`を使用した場合のこのルールの**正しい**コードの例
class OtherClass {
static log() {
console.log(OtherClass);
}
}
// With `ignoreStatic`, statics are assumed to not rely on a particular scope
const { log } = OtherClass;
log();
Playgroundで開く使用しない場合
プロジェクトで`this`スコープを動的に変更する方法をTypeScriptがモデリングしにくい場合、このルールは使用できない場合があります。たとえば、`Reflect.apply`や`Array.prototype.map`などの配列メソッドなど、一部の関数は`this`コンテキストを指定するための追加のパラメーターを持っています。このセマンティクスは、TypeScriptでは簡単に表現できません。このルールを完全に無効にする代わりに、ESLintの無効化コメントをそれらの特定の状況で使用することを検討してください。
Jestテストで`toBeCalled`や同様のマッチングを使用する場合は、テストファイルでこのルールを無効にして、eslint-plugin-jest
のバージョンのこのルールを使用できます。
型チェックされたlintルールは従来のlintルールよりも強力ですが、型チェックされたlintingの設定も必要です。型チェックされたルールを有効にした後にパフォーマンスの低下が発生する場合は、パフォーマンスに関するトラブルシューティングを参照してください。