13

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!

top 5 comments
sorted by: hot top controversial new old
[-] towerful@programming.dev 3 points 5 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)

[-] arendjr@programming.dev 5 points 5 months ago

Generally, I would recommend against throwing in the default case, since it will actually reduce your type safety (exceptions bypass all your other types). But I learned that with another clever trick this can be avoided, giving both runtime and compile time safety: https://exploringjs.com/tackling-ts/ch_enums.html#exhaustiveness-checks

[-] sbv@sh.itjust.works 2 points 5 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.

[-] sloppy_diffuser@sh.itjust.works 2 points 4 months ago

There is support for this in Effect as another implementation.

https://effect.website/docs/guides/style/pattern-matching

[-] dracs@programming.dev 2 points 5 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.

this post was submitted on 15 Mar 2024
13 points (93.3% liked)

TypeScript

709 readers
3 users here now

founded 1 year ago
MODERATORS