如何解决在TypeScript中将静态方法引用传递给超级构造函数时,避免“ unbound function” ESLint警告
我有一个类,必须使用作为参数传递的函数来调用其超类。我想从同一类传递静态函数:
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警告中所述的问题?
解决方法
有几种方法可以解决此问题:
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。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。