Sign in

Tricks to simplify the IF/Switch condition in Typescript

I had thought about writing the blog for many months but I did not know where to start or what to write. But finally, I thought I will start with a simple concept of how IF/SWITCH conditions can be minimized. We will look into it case by case.
I had refactored many of the code. I tried to resize the long code to a minimum without losing readability. And it's fun :D.

I believe code should be in such a way that you don’t need to write comments to make the code readable. The code itself should be self-explanatory. I look at the comments as functionality explanation rather than how the functionality is implemented.

So let's get into the code :D. The below code has IF condition where it checks for multiple string condition values. And then does the action based on the value. There are many ways to simplify it, and it may not be applicable always.

All the conditions if you look at it are checking with string values and are OR conditions. So we can refactor like below,

It can be made more beautiful and maintainable with switch condition.

I always prefer switch condition over the long if-else condition. We will look into the more complex version which will have a combination of OR and AND condition in the next blog. Let me know your thoughts on the comment section.