Typescript 重构开关语句类型脚本
有没有更好的方法在typescript中编写switch语句?我在组件中有以下代码:Typescript 重构开关语句类型脚本,typescript,design-patterns,Typescript,Design Patterns,有没有更好的方法在typescript中编写switch语句?我在组件中有以下代码: switch (actionType) { case Type.Cancel { this.cancel(); break; } case Type.Discard { this.discard(); break; } case Type.Delete { this.delete();
switch (actionType) {
case Type.Cancel {
this.cancel();
break;
}
case Type.Discard {
this.discard();
break;
}
case Type.Delete {
this.delete();
break;
}
}
我一直在阅读有关策略和/或工厂模式的文章,但这意味着要为每个案例创建不同的类。就我而言,我不太确定这是否是最好的方法,但任何关于这个主题的建议都是非常受欢迎的。一个好的折衷办法是从
类型
到函数:
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)();
}
}
}
private map = new Map<Type, () => void>([
[Type.Cancel, this.cancel],
[Type.Discard, this.discard],
[Type.Delete, this.delete]
]);