动态调用存储在文本中的成员函数是否是 TypeScript 反模式?



在我的 Angular 组件类中,我有以下模式用于处理事件:

private keyHandlers = {
'ArrowDown': function ($event) {
this.handleArrowDown($event);
},
'ArrowUp': function ($event) {
this.handleArrowUp($event);
},
};

然后是这样的@HostListener

@HostListener('keydown', ['$event'])
onKeyDown($event: KeyboardEvent) {
if (typeof this.kbdHandlers[$event.code] === 'function') {
this.keyHandlers[$event.code]($event);
}
}

然后,再往下,我将那些单独的处理程序指定为类的私有成员:

private handleArrowDown($event) {
// ...
}
private handleArrowUp($event) {
// ...
}

然而,"noUnusedLocals": true,规则似乎不喜欢它,抱怨从未使用过handleArrow*方法。所以我的问题是 - 这种方法在 TypeScript 中被认为是一种反模式,还是有办法满足编译器并注意到这些成员?

答案是肯定的和否定的。

TypeScript 不鼓励动态引用,因为它无法分析您的代码并检测此类使用情况。因此,不幸的是,在这种情况下它会抱怨。

它有帮助你的良好意图,但它没有做正确的事情。或者换句话说,它没有足够的知识来做正确的事情。

另一方面,它绝对不应该"禁止"这种使用,因为TypeScript是JavaScript。因此,应该有一种方法可以缓解这种情况。

事实上,它正在讨论中:https://github.com/Microsoft/TypeScript/issues/9448

现在,我建议关闭noUnusedLocals(我知道,这很痛苦。无论哪种方式都很痛(。

@jmlopez指出,这里有两个替代解决方案:

export class SomeComponent {
private keyHandlers = {
// Specifying `this` will be processed by the compiler to make the function as used.
'ArrowDown': function (this: SomeComponent, $event) {
this.handleArrowDown($event);
},
// Arrow function will have the same effect.
'ArrowUp': ($event) => {
this.handleArrowUp($event);
}
}
onKeyDown($event) {
if (typeof this.keyHandlers[$event.code] === 'function') {
this.keyHandlers[$event.code]($event);
}
}
private handleArrowDown(_event) {
// ...
}
private handleArrowUp(_event) {
// ...
}
}

最新更新