DEV Community

Cover image for Replace Switch statement with Record - Typescript
devlazar
devlazar

Posted on

Replace Switch statement with Record - Typescript

Table Of Contents
* 📢ANNOUNCEMENT
* 🚀INTRO
* ⚙IMPLEMENTATION
* 👨🏻‍💻CODESANDBOX
* 🤔CONCLUSION
* 🙏THANK YOU

📢 ANNOUNCEMENT!

Hello coding dudes and dudesses! Hope you are all well and healthy. It's been quite a difficult time around the globe. I haven't been active for some time. I want to announce that I will communicate with you (through blogs) more often and try to tackle coding, engineering and business with you. Without further ado, let's get into it!

journey

🚀 INTRO

So, you probably came across a situation where you have something like this:

switch(someVariable: string) {
   case 'someValue': 
        ....
        break;
   case 'someOtherValue':
        ....
        break;
   case 'somethingElse':
        ....
        break;
   ...
}
Enter fullscreen mode Exit fullscreen mode

You probably did, right? Well, there is nothing wrong about this, It is perfectly correct way of replacing the If statement. But we can notice that this can also get a bit hard to follow and manage. With the power of TypeScript we can actually make this even simpler.

⚙ [IMPLEMENTATION]

Let's consider that each case within the switch statement usually and in the best case has three lines of code.

case 'valueToCompareWith':       //first line
      someFunctionToExecute();  //line two
      break;                     //third line
Enter fullscreen mode Exit fullscreen mode

Example
We have an assignment:

  • We should fetch some financial or product data using two different functions (handlers) that someone provided for us. Let's say getFinancialData() and getProductData().
  • For this occasion we are currently using the same indicator, let's call it dataHandlerIndicator and it will be of type 'financial' | 'product'.

Let's make a switch statement for this example

type DataType = 'financial' | 'product';
const dataHandlerFunction = (dataHandlerIndicator: DataType) => {
   switch(dataHandlerIndicator) {
      case 'financial':
         getFinancialData();
         break;
      case 'product':
         getProductData();
         break;
   }
} 
Enter fullscreen mode Exit fullscreen mode

So, for these two different DataType types we have 6 lines of code handling it and making it fairly easy to read. If we had 3 types we would have 9 lines of code, and for 10 different data types, well we all understand maths, we will have ~ 30 lines of code, maybe even more if we add some additional logic to the case statement.

Let's simplify this by using Record!

// functions to be called
const getFinancialData = () => {
    console.log('Fetch financial data...');
}

const getProductData = () => {
    console.log('Fetch product data...');
}
// end functions to be called ...

type DataType = 'financial' | 'product';

const getDataSelector: Record<DataType, () => void> = {
   'financial': getFinancialData,
   'product': getProductData
}

const dataHandlerFunction = (dataHandlerIndicator: DataType) => {
   getDataSelector[dataHandlerIndicator]()
}

dataHandlerFunction('product'); // 'Fetch product data...'
dataHandlerFunction('financial'); // 'Fetch financial data...'
Enter fullscreen mode Exit fullscreen mode

TRY OUT THE CODESANDBOX EXAMPLE

🤔 CONCLUSION

Now, we can see that with the Record we have two lines of code describing the functions that will be called based on the DataType key value, and we have one line getDataSelector[dataHandlerIndicator]() that will call corresponding function based on the dataHandlerIndicator we pass to the function. Pretty neat, right!?

  • We reduced number of lines
  • Our code is much more readable
  • In order to add additional functionality, just update the Record with the new (key, value) pair, and that's it, you have a new selector for fetching new data based on the data type selector.

🙏 THANK YOU FOR READING!

Please leave a comment, tell me about you, about your work, comment your thoughts, connect with me!

☕ SUPPORT ME AND KEEP ME FOCUSED!

Buy Me a Coffee at ko-fi.com

Have a nice time hacking! 😊

Latest comments (0)