![](/img/trans.png)
[英]TypeScript NextPage function getInitialProp static method with @typescript-eslint/unbound-method
[英]Avoid 'unbound function' ESLint warning when passing a static method reference to a super constructor in TypeScript
我有一個 class 必須使用作為參數傳遞的 function 調用其超類。 我想從同一個 class 傳遞一個 static function:
export abstract class ChildAdapter extends Adapter{
protected constructor() {
super(ChildAdapter.index);
}
static async index() {...}
我收到了 ESLint 警告: ESLint: Avoid reference unbound methods 這可能會導致無意的范圍界定this
.(@typescript-eslint/unbound-method) 。
一種選擇是在此處使用某種外部全局 function,但我希望將所有方法封裝在 class 中,以便將它們放在一起。 我無法重構代碼,因此對super()
的調用不包含 function 引用。
我很困惑為什么 ESLint 警告我 static function 因為它根本沒有“這個”。 我該怎么做才能避免 ESLint 警告中所述的問題?
有幾種方法可以解決此問題:
export abstract class ChildAdapter extends Adapter{
protected constructor() {
super(ChildAdapter.index.bind(ChildAdapter);
}
static async index() {...}
或者:
export abstract class ChildAdapter extends Adapter{
protected constructor() {
super(() => ChildAdapter.index());
}
static async index() {...}
或者:
export abstract class ChildAdapter extends Adapter{
protected constructor() {
super(ChildAdapter.index);
}
static index = async () {...}
對於未來的讀者,這里討論了 Eslint 發出此警告的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.