Typescript Syntactic Sugar for Cleaner Code

Utkarsha Bakshi
2 min readJul 30, 2020

--

Have you ever wondered/questioned/wished that how many code of lines you can save by escaping the if-else hell?? Well, isn’t it every coder wish to make their code look cleaner and optimised?. This article will help you understand some ways where you can actually reduce the number of lines in your code by eliminating the regular If-else syntax and writing some cool and optimised stuff.

I am going to go through various examples that I have learned from my experience:

Example 1: Returning boolean without using true/false keywords.

function getName(name) {  
return name.indexOf('John') > -1 ? true : false;
}
getName('John Doe');
// It Will return true

Now lets see how we can optimise this:

function getName(name) {  
return !!(name.indexOf('John') > -1);
}

In above example we eliminated the need of if-else shorthand. With the help of “!!”, that statement got eliminated and the above function will give you the same results and the function looks bit cleaner too.

Now, let’s see the second example,

Example 2: How can “&&” usage be saved from the code??

const resp = {
"err": {"code": 400 }
}
if (resp && resp.err && resp.err.code) {
// do something
}

We can remove all the “&&” like this:

if (resp ?.err ?.code) {
// do something
}

Yup, you see it right, with two ?, we were able to shorthand a lengthy statement. ? is the indication that the next value written to it “may or may not” be present and your code will not break if the it is not present and it will not enter the if-block at all.

Example 3: Using if-else smartly

I was saving the best for the last because this example will really be helpful. If you are a simple if-else user, I am pretty sure this will blow your mind. Let’s dig in. If you have a piece of code which looks like this:

let limit = 5;
while(true){
if (typeof limit !== 'undefined') {
if (limit > 0) {
limit = limit - 1;
} else {
break;
}
}
}

This is how it can be optimised, in one line:

let limit = 5;
while(true){
if (--(limit as number) < 0) break;
}

Both pieces of code does the same work:

  1. Checking type is undefined or not.
  2. Decrease the limit by 1, if greater than zero.
  3. Break the loop if the condition is not met.

But you can see how we did optimise the number lines in the code.

So, these are some ways that you can use to refactor your code sections which are using if-else statements. I hope this article has helped you in learning something new.

--

--