Hacker News new | past | comments | ask | show | jobs | submit login

Your second example is not how anyone here is recommending using an object to replace a switch. You've still got the function call, which is now redundant.

Here's how you'd actually do it:

    type CountryCode =
      | "CH"
      | "US";


    const countryNames: Record<CountryCode, string> = {
      "CH": "Switzerland",
      "US": "United States of America",
    }
Your second example is way more complicated than your first, but this one is even easier to read (at least for me), and still provides all the same functionality and type safety (including exhaustiveness checking).



Consider applying for YC's Summer 2025 batch! Applications are open till May 13

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: