flightcontrolhq / superjson

Safely serialize JavaScript expressions to a superset of JSON, which includes Dates, BigInts, and more.
https://www.flightcontrol.dev?ref=superjson
MIT License
4.02k stars 87 forks source link

How to Parse and Stringify without losing types? #198

Closed mcgrealife closed 2 years ago

mcgrealife commented 2 years ago

Does anyone know how to parse and stringify without the result type being 'any' or 'unknown'?

In my case, I am using Prisma in NextJS data fetching models. I can workaround by type casting the parsed and stringified result back to a Prisma generated type, but it is not flexible to type changes.

Maybe there are some typescript keywords that can help it infer from the prototype?

mcgrealife commented 2 years ago

I found the solution with tRPC. The "decimal" recipe on the readme was also helpful.

For a drop-in tRPC transformer solution, this tRPC-transformer package exports superjson with the custom decimal recipe already registered

Using superjson with the decimal recipe is working for me in next@12.1.0 using the babel plugin, AND on next@latest (12.2.5) using the experimental SWC plugin!

Thanks for a great package.