Replace Switch statement with Record - Typescript
Tags: typescript, webdev, programming, javascript
Published: 2022-03-13 13:20:59

Table Of Contents
        * 📢[ANNOUNCEMENT](#announcement)
        * 🚀[INTRO](#intro)
        * ⚙[IMPLEMENTATION](#implementation)
        * 👨🏻‍💻[CODESANDBOX](#codesandbox-example)
        * 🤔[CONCLUSION](#conclusion)
        * 🙏[THANK YOU](#thank-you)


## 📢 ANNOUNCEMENT! <a name="announcement"></a>

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](https://media.giphy.com/media/r4SG84QtRlW0g/giphy.gif)

## 🚀 INTRO <a name="intro"></a>

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

```typescript
switch(someVariable: string) {
   case 'someValue': 
        ....
        break;
   case 'someOtherValue':
        ....
        break;
   case 'somethingElse':
        ....
        break;
   ...
}
```

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] <a name="implementation"></a>

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

```typescript
case 'valueToCompareWith':       //first line
      someFunctionToExecute();  //line two
      break;                     //third line
```

**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
```typescript
type DataType = 'financial' | 'product';
const dataHandlerFunction = (dataHandlerIndicator: DataType) => {
   switch(dataHandlerIndicator) {
      case 'financial':
         getFinancialData();
         break;
      case 'product':
         getProductData();
         break;
   }
} 
```

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!

```typescript
// 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...'
```

**TRY OUT THE CODESANDBOX EXAMPLE** <a name="codesandbox-example"></a>

{% codesandbox replace-switch-statement-with-record-typescript-usq1fe %}

## 🤔 CONCLUSION <a name="conclusion"></a>

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!<a name="thank-you"></a>

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

☕ SUPPORT ME AND KEEP ME FOCUSED!

<a href='https://ko-fi.com/Z8Z33D1HJ' target='_blank'><img height='36' style='border:0px;height:36px;' src='https://cdn.ko-fi.com/cdn/kofi4.png?v=2' border='0' alt='Buy Me a Coffee at ko-fi.com' /></a>

Have a nice time hacking! 😊