Jus*_*ant 8 typescript typescript-eslint
下面的代码不使用类或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;
}
Run Code Online (Sandbox Code Playgroud)
Jus*_*ant 16
通过简单地替换为bar(): void,这个问题非常容易解决bar: () => void。
例子:
interface FooProps {
bar: () => void;
}
export function foo(props: FooProps) {
const { bar } = props; // no lint error
return bar;
}
Run Code Online (Sandbox Code Playgroud)
我一直想知道为什么 TypeScript 接口的函数值成员有两种不同的语法。我一直认为这两种语法具有相同的含义。现在我更bar(): void清楚了:语法显然表示“类成员函数”,而bar: () => void表示“不使用的函数值属性this”。
在这里留下一个问答对,这样下一个受害者就不会像我那样浪费半个小时了。
| 归档时间: |
|
| 查看次数: |
3695 次 |
| 最近记录: |