繁体   English   中英

将 static 方法引用传递给 TypeScript 中的超级构造函数时避免“未绑定函数”ESLint 警告

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM