gvergnaud / ts-pattern

🎨 The exhaustive Pattern Matching library for TypeScript, with smart type inference.
MIT License
12.24k stars 129 forks source link

.safeExhaustive #218

Open jjhiggz opened 9 months ago

jjhiggz commented 9 months ago

Is your feature request related to a problem? Please describe.

In my app that I'm working on, I love the developer experience of exhaustive checks, because they force me to handle all of the edge cases that I need. But too often I am encountering scenarios where something doesn't migrate quite right, my runtime type becomes slightly different than my compile time type, and then I get a production error and have to switch from exhaustive to otherwise.

Describe the solution you'd like

It would be extremely awesome if there was a safer alternative to .exhaustive that provided the same developer experience in typescript. To me this would look something like this:

type MyUnion = "a" | "b"

const a = "" as MyUnion

match(a)
  .with(("a") => "you chose a")
  .with(("b") => "you chose b")
  .safeExhaustive(
     "a" // <= default  if error is thrown by patern match,
     console.error // a callback that allows us to handle the error throw by pattern matching
  )

Describe alternatives you've considered Using .otherwise

In a perfect world (I know this is probably a bigger ask), it would be cool if we could create a customized instance of match so we wouldn't have to dump in a callback every time or something like that. But I imagine that's a much bigger lift than just building a .safeExhaustive method

Liam-Tait commented 8 months ago

Similar to https://github.com/gvergnaud/ts-pattern/issues/144. This would cover my issue.