有没有更好的方法在打字稿中编写 switch 语句?我在一个组件中有以下代码:
switch (actionType) {
case Type.Cancel {
this.cancel();
break;
}
case Type.Discard {
this.discard();
break;
}
case Type.Delete {
this.delete();
break;
}
}
我一直在阅读有关策略和/或工厂模式的信息,但这意味着为每种情况创建不同的类。就我而言,我不太确定这可能是最好的方法,但非常欢迎有关此主题的任何建议。
一个很好的中间立场是从Type
函数到函数的映射:
class Test {
private map = new Map<Type, () => void>([
[Type.Cancel, () => this.cancel()],
[Type.Discard, () => this.discard()],
[Type.Delete, () => this.delete()]
]);
yourMethod(actionType: Type) {
if (this.map.has(actionType)) {
this.map.get(actionType)();
}
}
}
如果方法已经绑定(使用箭头函数bind
等),您可以简化为:
private map = new Map<Type, () => void>([
[Type.Cancel, this.cancel],
[Type.Discard, this.discard],
[Type.Delete, this.delete]
]);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句