9

下面的代码不使用类或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;
}
4

1 回答 1

19

这个问题很容易通过简单地替换来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”。

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

于 2020-07-12T18:20:01.037 回答