【问题标题】:Avoid 'unbound function' ESLint warning when passing a static method reference to a super constructor in TypeScript将静态方法引用传递给 TypeScript 中的超级构造函数时避免“未绑定函数”ESLint 警告
【发布时间】:2020-08-17 11:36:09
【问题描述】:

我有一个类必须使用作为参数传递的函数来调用它的超类。我想从同一个类中传递一个静态函数:

export abstract class ChildAdapter extends Adapter{

  protected constructor() {
    super(ChildAdapter.index);
  }

  static async index() {...}

我收到了 ESLint 警告:ESLint:避免引用未绑定的方法,这可能会导致无意中对 this.(@typescript-eslint/unbound-method) 进行范围界定

一种选择是在这里使用某种外部全局函数,但我希望将所有方法封装在类中,只是为了让事情保持在一起。我无法重构代码,因此对super() 的调用不包含函数引用。

我很困惑为什么 ESLint 警告我静态函数,因为它根本没有“this”。如何避免 ESLint 警告中所述的问题?

【问题讨论】:

  • 你可以通过 ChildAdapter.index.bind(ChildAdapter) (...或 () => ChildAdapter.index() 以牺牲一点间接性为代价)。
  • 这个警告告诉你一些重要的事情。 static 方法可以使用 this,这是类本身,并且经常这样做,因此您必须像任何其他方法一样绑定它们。
  • ...确实,总是有一个this,并且随时注意它是值得的。如果您感到困惑,值得一读:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • @spender 随时回答,我会接受的:) 但是,只有绑定版本对我有用,()=>... 发出警告。真正的 index() 函数有一些参数和泛型。

标签: typescript eslint


【解决方案1】:

有几种方法可以解决此问题:

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 发出此警告的原因已在 here 进行讨论。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-25
    • 1970-01-01
    • 1970-01-01
    • 2019-03-18
    • 2012-02-21
    相关资源
    最近更新 更多