ts-pattern icon indicating copy to clipboard operation
ts-pattern copied to clipboard

Idea: Compile match() to zero-runtime if/switch via Babel/TS plugin for worklet-safe and embedded use

Open salemkode opened this issue 8 months ago • 1 comments

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

I'm frustrated that ts-pattern.match() cannot be used inside runtime-restricted environments like React Native Reanimated worklets. These environments require that all logic be serialized or statically analyzable, and they reject any dynamic closures or higher-order functions. This makes it impossible to use match() inside "worklet" functions, which limits its utility in animations, embedded interpreters, or performance-critical UIs — even though ts-pattern's syntax and exhaustiveness checks are perfect for these cases.

Describe the solution you'd like

I'd like to see an official Babel plugin or TypeScript transformer that compiles match() expressions into native if / else if / switch statements at build time, when the input patterns are statically known. This would make ts-pattern usable in constrained environments (like Reanimated worklets) while preserving type safety and syntax clarity.

The output would eliminate the runtime cost and make the pattern-matching fully static — essentially transforming ts-pattern into a zero-runtime, zero-dependency DSL in supported use cases.

Describe alternatives you've considered

  • Manually rewriting match() logic as if/switch inside worklets — but this loses the type-safe benefits and expressiveness of ts-pattern.
  • Precomputing the result of match() outside the worklet and passing primitives in — this works, but breaks reactivity and tight code locality.
  • Avoiding ts-pattern in these contexts entirely — which defeats its ergonomic and safety goals.

Additional context

This kind of transformation would be similar in spirit to:

  • linaria (zero-runtime CSS-in-JS)
  • babel-plugin-macros
  • vanilla-extract
  • or solid-js's reactive compiler

Even just a plugin that supports a basic subset (e.g., literal matches only, no P.when) would unlock valuable use cases — especially in React Native and embedded JS environments.

Happy to contribute ideas or help with a proof of concept if this direction is interesting for the project!

Thanks again for the amazing library 🙏

In our codebase, we are actively working to eliminate all traditional if/switch statements and replace them with type-safe match() expressions — inspired by ideas from languages like OCaml, ReScript, and other ML-family languages. Maintaining strict type safety and functional clarity is a core goal in our project.

salemkode avatar May 12 '25 06:05 salemkode

https://github.com/aidenybai/pattycake there was a attempt for this.

JUSTIVE avatar Jun 11 '25 01:06 JUSTIVE