Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 重构开关语句类型脚本_Typescript_Design Patterns - Fatal编程技术网

Typescript 重构开关语句类型脚本

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();

有没有更好的方法在typescript中编写switch语句?我在组件中有以下代码:

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]
  ]);