Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 1368

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 62k
Author
Asked: November 25, 20242024-11-25T07:31:06+00:00 2024-11-25T07:31:06+00:00

Replace Switch statement with Record – Typescript

  • 62k

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! 😊

javascriptprogrammingtypescriptwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.