unbound-method
強制未繫結方法會以預期的範圍呼叫。
✅
擴充 "plugin:@typescript-eslint/recommended-type-checked"
在 ESLint 設定檔 中啟用這項規則。
💭
這項規則需要 類型資訊 才能執行。
當傳遞作為獨立變數(「未繫結」)時,類別方法函數不會保留類別範圍。如果你的函數不會存取 this
,你可以透過 this: void
加以註解,或考慮改用箭頭函數。否則,將類別方法當成值傳遞可能會因為沒能捕捉到 this
而移除類型安全性。
此規則會在未繫結方式中參照類別方法時回報。
提示
如果您使用的是 jest
,則可以使用 eslint-plugin-jest
's 的此規則版本 來約束您的測試檔案,而它知道何時可以傳遞未繫結的方法給 expect
呼叫。
。eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/unbound-method": "error"
}
};
在遊樂場中嘗試此規則 ↑
範例
- ❌ 錯誤
- ✅ 正確
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;
在遊樂場中開啟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;
在遊樂場中開啟選項
此規則接受以下選項
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();
在遊樂場中開啟何時不使用它們
如果您的專案動態地變更在 TypeScript 難以建模的 this
範圍,則此規則可能無法使用。例如,某些函數有指定 this
環境的附加參數,例如 Reflect.apply
,以及陣列方法,如 Array.prototype.map
。此語意並不容易由 TypeScript 表達。您可以考慮在那些具體情況下使用 ESLint 停用註解,而不是完全停用此規則。
如果您想在 jest
測試中使用 toBeCalled
和類似的比對,您可以停用您的測試檔案中的此規則,以利於 eslint-plugin-jest
's 此規則版本。
類型檢查約束規則比傳統約束規則更強大,但同時也需要設定 類型檢查約束。如果您在啟用類型檢查規則後遇到效能惡化,請參閱 效能疑難排解。