How to assign a variable to switch statement result

It’s a helpful trick that allows writing compact yet highly type-proof code to deal with enums both in TypeScript and Flow.

const result = (function () {
  switch (step) {
    case Step.One:
      return { one: 1 };
    case Step.Two:
      return { two: 2 };
    case Step.Three:
      return { three: 4 };
  }
})();

I use in React render as well.

#javascript #typescript #flow

***

Since you've made it this far, sharing this article on your favorite social media network would be highly appreciated 💖! For feedback, please ping me on Twitter.

Published