Today I’m sharing a little trick that I like to use to make switch statements cleaner and more type-safe. Happy to hear other ideas!

  • towerful@programming.dev
    link
    fedilink
    arrow-up
    2
    ·
    8 months ago

    Just have default throw an error? Then, if you add a value to the string union (hopefully) your tests will highlight it isnt handled.

    Equally, for such a simple switch, surely a map is better?
    But i rarely find myself using switches.
    I find ifs with early returns cleaner. Allows for variable creation during execution (which my tslint complains about)

    • sbv@sh.itjust.works
      link
      fedilink
      English
      arrow-up
      2
      ·
      8 months ago

      I really appreciate compile errors in this scenario. In Rust the compiler will freak out when there are missing enum variants in a match. Tests are great, but compiler errors don’t rely on exhaustive and properly written tests.

  • dracs@programming.dev
    link
    fedilink
    English
    arrow-up
    2
    ·
    8 months ago

    I haven’t had a chance to try it myself yet. I saw someone give a recommendation for ts-pattern which provides functions for pattern matching with optional exhaustion.