Rocshy
Rocshy

Reputation: 3509

Refactoring switch statement typescript

Is there a better way to write a switch statement in typescript? I have this following code in a component:

switch (actionType) {
    case Type.Cancel {
        this.cancel();
        break;
    }
    case Type.Discard {
        this.discard();
        break;
    }
    case Type.Delete {
        this.delete();
        break;
    }
}

I've been reading about the strategy and/or factory pattern, but that would mean creating different classes for each case. In my case I'm not so sure it might be the best approach but any advice regarding this topic is very welcomed.

Upvotes: 0

Views: 1430

Answers (1)

Frank Modica
Frank Modica

Reputation: 10526

A nice middle ground is to have a map from the Type to the function:

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

If the methods are already bound (with an arrow function, bind. etc.) you can simplify like:

  private map = new Map<Type, () => void>([
    [Type.Cancel, this.cancel],
    [Type.Discard, this.discard],
    [Type.Delete, this.delete]
  ]);

Upvotes: 2

Related Questions