【问题标题】:How to prevent "@typescript-eslint/unbound method" errors on non-class TypeScript interfaces?如何防止非类 TypeScript 接口上的“@typescript-eslint/unbound method”错误?
【发布时间】:2020-11-02 00:03:59
【问题描述】:

下面的代码不使用类或this。如何防止仅函数(无类)代码中的 typescript-eslint 错误?我知道我可以全局禁用该规则,但该规则对类代码很有用。我知道我可以一次禁用它一行,但考虑到在 TS 接口中定义回调函数是多么普遍,这似乎很痛苦。还有其他方法吗?

这是问题的简化示例:

interface FooProps {
  bar(): void;
}

export function foo(props: FooProps) {
  const { bar } = props;
  // ^^^ Avoid referencing unbound methods which may cause unintentional scoping of `this`.
  //     eslint(@typescript-eslint/unbound-method)
  return bar;
}

【问题讨论】:

    标签: typescript typescript-eslint


    【解决方案1】:

    只需将bar(): void 替换为bar: () => void 即可轻松解决这个问题。

    例子:

    interface FooProps {
      bar: () => void;
    }
    
    export function foo(props: FooProps) {
      const { bar } = props;  // no lint error
      return bar;
    }
    

    我一直想知道为什么 TypeScript 接口的函数值成员有两种不同的语法。我一直认为这两种语法具有相同的含义。现在我知道了:bar(): void 语法显然表示“类成员函数”,而 bar: () => void 表示“不使用 this 的函数值属性”。

    在这里留下一个问答对,这样下一个受害者就不会像我那样浪费半个小时了。

    【讨论】:

    • 我希望我只浪费了半个小时!
    • 所以归根结底,一切都归结为语法??多么愚蠢。我正在禁用此规则。此外,我认为您对接口中函数的最初假设是正确的。我没有读到任何打字稿对接口中函数类型的实现做出任何假设的地方。以我的经验,接口只是告诉你对象的形状,而不是它的实现方式。使用常规函数语法来声明函数的类型并不意味着函数内部的“this”将始终与包含该函数的对象相关联
    猜你喜欢
    • 2020-06-13
    • 2018-08-24
    • 2013-09-19
    • 2021-02-05
    • 2019-04-27
    • 2022-09-28
    • 2023-03-04
    • 2023-02-07
    • 2016-02-22
    相关资源
    最近更新 更多