Zod: TypeScript-first schema validation with static type inference
zod.dev
zod.dev
Previously I liked a combination of Zod and ts-pattern to create safe, pattern matching-oriented logic around my data. I find Effect is designed far better for this, so far. I'm enjoying it a lot. The Schema module has a nice convention for expressing validators, and it's very composable and flexible: https://effect.website/docs/guides/schema/introduction
There are also really nice aspects like the interoperability between Schema and Data, allowing you to safely parse data from outside your application boundary then perform safe operations like exhaustively matching on tagged types (essentially discriminated unions): https://effect.website/docs/other/data-types/data#is-and-mat...
It feels extremely productive and intuitive once you get the hang of it. I didn't expect to like it so much.
I think the real power here is that these modules also have full interop with the rest of Effect. Effects are like little lazy loaded logical bits that are all consistent in how they resolve, making it trivial to compose and execute logic. Data and Schema fit into the ecosystem perfectly, making it really easy to compose very resilient, scalable, reliable data pipelines for example. I'm a convert.
Zod is awesome if you don't want to adopt Effect wholesale, though.
I think the real turning point was typescript 5.5 (May 2024). The creator of typescript personally fixed a bug that unlocked a more natural generator syntax for Effect, which I think unlocks mainstream adoption potential.
https://twitter.com/MichaelArnaldi/status/178506160889445172... https://github.com/microsoft/TypeScript/pull/58337
I wouldn't use Effect for a lot of things. For some things, I'm very glad to have it. One thing Effect has going for it that Ramda didn't is that it's much less abstract and it's quite a bit more opinionated about some more complex concepts like error handling, concurrency, or scheduling.
Kind of like state machines. You shouldn't use them for everything. For some things, it's a bad idea not to (in my opinion).
Then of course subjectivity is a factor here. Some people will never like conventions like Effect, and that's fine too. Just write what feels right.
I liked the idea of Ramda until I saw code bases that where using it for everything.
I'm doing JS for over a decade now and I couldn't understand a thing.
Having experience with ZIO / FP in Scala, I'm a bit biased in seeing the value of Effect systems as a whole, but taking on the burden of explaining that mental model to team members and future maintainers is a big cost for most teams.
Is 'retry / observability / error handling" something that comes from Effect?
Retrying[0], observability[1], and error handling[2] are first-class concerns and have built-in combinators to make dealing with those problems quite ergonomic. Having these features is a non-starter for any serious application, but unfortunately, the story around them in the TypeScript ecosystem is not great—at least as far as coherence goes. You often end up creating abstractions on top of unrelated libraries and trying to smash them together.
I'm a big fan of ReasonML / OCaml, and I think the future of TypeScript will involve imitating many of its code patterns.
[0] https://effect.website/docs/guides/error-management/retrying
[1] https://effect.website/docs/guides/observability/telemetry/t...
[2] https://effect.website/docs/guides/error-management/expected...
Our team is full effect from two years and juniors can pick it and start working on it with ease.
For the love of god just use User / RegisteredUser / GuestUser and other abstractions that have some basis in the real world.
Solutions like effect are easier to appreciate as your application starts growing in complexity beyond simple todo apps.
Solutions like effect/schema are easier to appreciate as soon as you start needing complex types, encoding/decoding, branded types and more.
I am quite confident that effect will keep growing in popularity steadily and eventually grow.
It took more than 5/6 years for TypeScript or React to start getting spread around the JS community. Effect is here to stay and I'm confident it will eventually be adopted by plenty of developers.
Nowadays I’d rather rely on libraries that don’t require a phd to use them properly.
This is 100% how to write more reliable software. We are in the process of reducing our TS dependencies to effectively just express and node-postgres and everything is becoming infinitely easier to manage.
I may simply be too dumb for lots of fancy functional programming. I can barely understand code when reading one line and statement at a time. Reading functions calling functions calling functions just makes me feel like gravity stopped working and I don't know which way is up. My brain too small.
It's the same effect as adding async code to Python or Rust, suddenly the entire team and the entire codebase (and often dependency choices) must adhere to it.
You can choose to make a single flow in your application an effect program. Or you can base most of your functions around it. It's really up to you how and where it's used. If you want to use an effect within non-effect code, that's easy to do, too.
You can think of effects like values. The value is obtained by executing the effect. Until it's called, the effect can be placed anywhere, in any function, in a generator, within promises, etc. Once you need its value, you execute it. It's compatible with most code bases as long as you can execute it to get the value. It's really up to the developer how portable they want their effects to be.
Passing Effects around will similarly infect the entire codebase, resulting in the entire dev team who interacts with it needing to buy in. Limiting the output of Effects to a single module owned by one zealot dev undermines having it around in the first place and it'll get removed and replaced as soon as that person leaves or gives up the fight.
The learning curve just about turned me away from it at the start, but I'm glad I stuck with it.
I think learning Effect would actually teach a lot of people some very useful concepts and patterns for programming in general. It's very well thought out.
Some core things from Effect though that you can see in that Express example:
* Break things down into Services. Effect handles dependency injection, that's typed, for services so you can easily test them and have different versions running for testing, production, etc. * Fibers for threaded execution * Managing resources to make sure they're properly closed with scope
I think a lot of these things though often aren't truly appreciated until you've had something go wrong before or you've had to build a system to manage them yourself. *
I fully agree parts of the ecosystem are complex, and likely not fully ready for broad adoption. But I do think things will simplify with time, patterns will emerge, and it will be seen as react-for-the-backend, the de facto first choice. effect + schema + platform + cluster will be an extremely compelling stack.
await fetch(…)
.catch(e =>
new CustomError(…))
But with a wrapped-promise and flatmap nonsense for “better error handling”.FP always goes out of the way to avoid using the language it operates in and to criticize the ways of doing something it just imagined. As if it wanted to stay as noble from unwashed peasants as it could, but has to do the same job to keep existing.
how to test () => makePayment()? (from the link)
You don’t. You test constituents like request body generation and response handling. It’s inside. You can’t test your Effect-version of this code neither. It’s a strawman.
It looks very similar in its ideas to fp-ts (in the “let’s bring monads, algebraic types etc to typescript” sense).
But I did hear from teams that embraced fp-ts that things kinda ground to a halt for them. And those were category theory enthusiasts that were very good scala devs so I’m sure they knew what they were doing with fp-ts.
What happened was that the typescript compile time just shot into minutes, for a moderately sized micro-service, without anything externally heavy being introduced like you could on the frontend.
It just turned out that Typescript compiler was not so great at tracking all the inferred types throughout the codebase.
So wonder if things have improved or effect uses types more intelligently so that this is not an issue.
It's the next version of fp-ts, developed by the same people, AFAIK
This way you can use native language features for discriminated unions, functional pipelines, and exhaustive pattern matching to model your domain instead of shoe-horning such functionality into a non-ML language!
Model your domain in F#, consume it in Python or C# backends and TypeScript frontends. The downside is needing to know all of these languages and run times but I think I'd rather know F# and the quirks with interacting with TypeScript than a library like Effect!
[1] https://fable.io
1. Debugging can become quite a pain. Nobody likes debugging generated code.
2. You don't get to use libraries and tools from the enormous JavaScript ecosystem.
3. Eventually you'll find some web feature that they haven't wrapped in your language and then you're in for FFI pain.
In the end I found Typescript was good enough that it wasn't worth dealing with those issues.
You can build an entire application in F# and compile to JS but another option is compiling to TS and calling that F# code from your TS app. I/O and views and whatnot are written in TS and the domain model is in F#. The entire model could be nothing but pure functions and resolve to a single expression!
Rather disappoint to see something like this being plugged as an alternative to something like zod which is a nice library that stays in its corner and has a nice fixed scope to it's functionality.
also since zod is the de facto validation lib, might be worth a specific page talking about why this vs zod. even their migration from zod page looks nearly identical between the two packages.
This feels like an issue that reduces down to the Halting Problem, though. Halting is a function that could be made a member of a class, so if you could tell whether that method is used or not then you could tell whether the program will halt or not. I think it's one of those things that feels like it should be fairly easy, and it's really really not.
I don't need to be able to eliminate every single unused function in every situation, but if I can prove that certain functions are unused then I can delete just those functions. We're already doing this regularly with standalone functions, so my question is just why this isn't done with class members.
Being able to access class members using square bracket syntax with a variable also seems like it would make it really difficult to prove that something isn’t used. I’m thinking something unhinged like using parameters to build a string named after a class member and then accessing it that way.
Dunno, I would be curious if someone has a definitive answer as well.
edit: The creator of Terser is working on flow analysis for his new minifier, according to him[1].
[1]: https://github.com/terser/terser/issues/1410#issuecomment-17...
In any case, this might actually be a good use for an LLM to post-process it into whatever style you want. I bet there's even a browser extension that could do it on-demand and in-place.
- I support the creation of schemas for any primitive data type.
- Among complex values I support objects, records, arrays, tuples as well as various other classes.
- For objects I provide various methods like pick, omit, partial and required.
- Beyond primitive and complex values, I also provide schema functions for more special cases.
Same for "Mental model", "Pipeline", "Parse data", "Infer types", "Methods" and "Issues" - I'll assume the other sections also follow this style. That's all not showing up for you?
While the LLM suggestion is nice, it's not something I'm comfortable with unless hallucinations are incredibly rare. Why would I use a library whose documentation I have to pass through an unreliable preprocessor to follow a normal style?
I honestly don't want my validation library to "tell a story" at the expense of documentation clarity. It's absolutely fine that this project uses it, I don't want to impose my view on them - I guess it's just not the validation library for me.
Not an issue for me, to be honest. Why does it bother you at all?
1. The biggest part is that I've simply never seen documentation written in this style, any mentions of "I" or "we" are usually explaining the choices made by the author(s). When skimming documentation I pay more attention to those parts. Here those parts don't have a comparable meaning.
2. The smaller part is that the writing style reminds me of the way brands use mascots with first-person writing to advertise to children. There's not really any other association I have with this way of writing, and it makes me feel like the author either isn't taking the project seriously, or me.
I'm not trying to argue that the documentation should be understood this way, or that it should be changed - but I've stumbled over this multiple times, and can't imagine that it's just me.
I think a more important issue is that Valibot hasn't reached 1.0 yet. But it looks like it's very close.
In the software field you get a large portion of people that don't buy into the concept of professionalism. For various reasons - chiefly the hacker culture and the easy of contributing to the "field" means the gauntlet one runs to become a "professional" isn't inherently a given.
As a whole this is a good thing but it does mean if you operate as a "professional" maybe sometimes you have to realize that something doesn't exactly gel with your ethos (case in point). It doesn't mean it is bad; just maybe not for you and yours.
There's still more at play, since I really keep visually stumbling over those sentences, but that seems to be more related to me. And you're absolutely right that this doesn't make the project objectively worse - I wish them best of luck and hope their approach to documentation helps others!
Zod doesn't (yet[0]) and it's been a pain point for me.
import * as v from 'valibot';
const OptionalKeySchema = v.object({ key: v.optional(v.string()) });
type t1 = v.InferInput<typeof OptionalKeySchema>; // { key?: string }
const UndefinedKeySchema = v.object({ key: v.undefinedable(v.string()) });
type t2 = v.InferInput<typeof UndefinedKeySchema>; // { key: undefined } type { foo: ... , bar: ..., ... } can't be assigned to type { foo: ..., bar: ... }. type { foo: ... bar: ..., ... } is missing the following properties from { foo: ..., bar: ..., ... }
Apart from repeating roughly the same type 4 times (which is a UX issue that's fixable), debugging computed types requires having a typescript interpreter in your head.I wonder if we had nominal runtime checked types, it could work better than the current design in terms of DX. Basically, the : Type would always be a runtime checked assertion. Zod certainly fills that gap, but it would be nicer to have it baked in.
The type system would not be as powerful, but when I'm writing Kotlin, I really don't miss the advanced features of Typescript at all. I just define a data class structure and add @Serializable to generate conversions from/to JSON.
More news about Haxe can be found here: https://haxe.io/ (the old blog is not updated AFAIK)
That said Haxe has externs, enabling you to target JS/PHP and use the rich ecosystem both langauges have. The best part of externs is that IF i only use 4 things from given package, i statically KNOW i only use these 4 things, and can refactor more easily, or even build the thing i need myself.
Also, there are many ways to make types opaque (not show their entire verbose structure).
If you write in TS to start with, you can use a more sane subset.
[0] https://github.com/DefinitelyTyped/DefinitelyTyped/blob/mast...
[1] https://github.com/DefinitelyTyped/DefinitelyTyped/blob/mast...
Typescript `as Foo` will not do anything at runtime, and it will just keep on going, then throw a type error somewhere else later (possibly across an async boundary).
You can, in theory use very strong lint rules (disallow `as` operator in favour of Zod, disallow postfix ! operator), but no actual codebase that I've worked on has these checks. Even the ones with the strictest checks enabled have gaps.
Not to mention, there's intentional unsoundness in the type system, so even if you wanted, you couldn't really create a save subset of TS.
Then there's the issue of reading the library types of some generic heavy code. When I "go to definition" in my fastify codebase, I see stuff like this
RouteHandlerMethod<RawServer, RawRequest, RawReply, RouteGeneric, ContextConfig, SchemaCompiler, TypeProvider, Logger>
Which expands to this export type RouteHandlerMethod<
RawServer extends RawServerBase = RawServerDefault,
RawRequest extends RawRequestDefaultExpression<RawServer> = RawRequestDefaultExpression<RawServer>,
RawReply extends RawReplyDefaultExpression<RawServer> = RawReplyDefaultExpression<RawServer>,
RouteGeneric extends RouteGenericInterface = RouteGenericInterface,
ContextConfig = ContextConfigDefault,
SchemaCompiler extends FastifySchema = FastifySchema,
TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault,
Logger extends FastifyBaseLogger = FastifyBaseLogger
> = (
this: FastifyInstance<RawServer, RawRequest, RawReply, Logger, TypeProvider>,
request: FastifyRequest<RouteGeneric, RawServer, RawRequest, SchemaCompiler, TypeProvider, ContextConfig, Logger>,
reply: FastifyReply<RouteGeneric, RawServer, RawRequest, RawReply, ContextConfig, SchemaCompiler, TypeProvider>
// This return type used to be a generic type argument. Due to TypeScript's inference of return types, this rendered returns unchecked.
) => ResolveFastifyReplyReturnType<TypeProvider, SchemaCompiler, RouteGeneric>Other languages somehow don't need types this complicated and they're still safer at runtime :shrug:
That's surprising. I've worked on a few codebases with reasonably mature TS usage and they've all disallowed as/!/any without an explicit comment to disable the rule and explain why the use is required there.
The "as Foo" construct is for you to tell TS that you know better than it, or that you deliberately want to bypass the type system. You can have a runtime check, but you have to write the code yourself (a type predicate), because TS doesn't write or change any JavaScript*, it just type-checks it.
I've certainly worked in new codebases where a relatively simple subset of TS types were used. Even then there were a few places the crazy type system was helpful to have. For example, we enforced that the names of the properties in the global configuration object weren't allowed to have consecutive uppercase letters!
(* with minor exceptions like transpiling for new JS features)
That shifts the complexity of doing that out of the runtime and into the Typescript preprocessor where it's not going to mess with your production instances.
I also don't think it's all that bad; it's a lot of generic types, but it doesn't appear to be doing anything particularly complicated.
I do think they get awful, though. This is something I've been hacking on that I'm probably going to rewrite https://pastebin.com/VszX3MyE It's a wrapper around Electron's IPC and derives a type for the client from the type for the server (has to have the same methods and does some type finagling to strip out the server-specific types). It also dynamically generates a client based on the server prototype. The whole thing rapidly fell into the "neat but too complicated to be practical" hole.
You're NOT assuming correctly. In Kotlin, this would be handled as an extension property on the Request type. You could write it just like normal code instead of extending some global ambient interfaces.
val Request.foo: Bar = whatever
get("/") { req.foo // just a method call }
You can CMD+Click on it and read the actual implementation (instead of generated type definitions).The Typescript ecosystem needs these complicated types because of some design choices (no type based dispatch). I suggest looking up how other languages solve these problems. You'll find that in typescript, you have to reach for complex types far sooner than in other languages.
That’s what I’m specifically talking about. Yours is just dependency injecting a type, which is more avoiding the existing types in the library. That would be the “wrapping” option I was talking about. You don’t need to extend the types if you’re just going to dependency inject them. You could just have an entirely separate object that you pass around at that point.
It’s not some kind of moral sin, but it is a kludge. The type system is now tied to the structure of your code, because scoping is now intrinsic to your types.
It’s not the end of the world, I’ve worked in similar systems, it just tends to have a heavy mental overhead at some point as you now have to keep scoping in mind as part of your types.
Iow, don't go to the definition of a web request handler. Go here: https://fastify.dev/docs/latest/Reference/TypeScript/
Other languages (libraries really) separate these parts, e.g. Spring Boot seems to hide routing away into a method decorator which infers the body type from a target signature and the server is somehow implied(? through a controller?..). Anyway, it's all there, just not in one place. It has nothing to do with Typescript, it's a js library legacy issue.
ts-morph provides an easy way to use the TypeScript Compiler API to view and edit the AST before compile. Once you get your head around the API, which has good examples but isn't thoroughly documented on the web.
It also has a companion library[2] for generating TypeBox validators from TypeScript definitions, which I'm currently using in an RPC library I'm working on.
[1]: https://github.com/sinclairzx81/typebox [2]: https://github.com/sinclairzx81/typebox-codegen
After doing a deep-dive comparison, I’m left wondering why to ever choose Zod over TypeBox.
Man why doesn’t it have a cli tool?? Wouldn’t it be nice to :'<'>!typeboxify a selection.
https://github.com/dittofeed/dittofeed/blob/main/packages/is...
I felt like I was being punished for everything. (Maybe some things were project specific so I am not saying this as an absolute) It's slow, syntax is horrible, error are obscure super long lines, it can compile and explode later (which is what elixir does, except elixir will happily restart and recover)...
Elixir is based on duck typing mostly, but it works very well because you just pattern match your data when you use it. Rust is very strict and can have cryptic errors, but as everything is baked in the language it is way easier to manage.
I am not saying this to be snob about typescript and JS, but I really felt pain when working with that ecosystem, and I wonder if I'm old and stupid or if those tools are really half baked and over complicated.
Thats not true. It just crashes the “sub” process and if the parent process spawns the sub process again with the same inputs its just going to crash again.
Are you aware you can also try/catch your errors in typescript?
The whole point of the library is to validate something at runtime so of course it is going to blow up. There are also API methods that simply return a boolean instead of crashing if it fails validation. You can then use type guarding and narrowing of the type.
The phone systems that Erlang's design emerged from naturally had these parallelism and distributed system properties that they could leverage and build on. Running Erlang on a single core SBC like to display virtual signage and limiting it to a single thread and not letting it have any redundancy in any way and then taking the approach of "let it crash" is not going to create a famously robust Erlang setup either, it's just going to create an Erlang-powered signage system that crashes and halts the same as any other runtime would. Erlang/OTP is a physical systems building and software design approach that you can't just put anywhere or bolt onto any arbitrary thing. You're not going to build an OTP-like Single Page Application because if you reliably crash the browser tab's process every time you start up, it's just going to keep crashing no matter how many times you refresh the page.
Zod feels like a crutch for limitations in Javascript and Typescript. But I've found it to be a very useful crutch, and I wouldn't want to write a Typescript API without it.
It is filling a necessary shortcoming in the gradual typing of TypeScript, and using validator schema types to power other APIs generic inference is powerful. I am optimistic about an obvious leader emerging, or at least a better story about swapping between them more easily, but a bit annoying when trying to pick one to settle on for work that I have confidence in. That being said, Zod seems like the community favorite at the moment.
Note that TypeScript had competitors, too. It got better. Zod has an early lead and is good enough in a lot of ways, but I'm not sure it will be the one.
Perhaps someday there will be a bun/deno-like platform with TypeScript++ that has validation merged in, but it's probably good that it's not standardized yet.
There are some performance issues, and WebStorm is struggling, which forced me over to VS Code.
But overall pretty happy.
It supports decoding as well as encoding, and fits natively into the rest of the effect ecosystem.
https://effect.website/docs/guides/schema/introduction
It does come with the cost of importing effect, so might not be the best in certain scenarios. However, there are smaller options than zod if that is a concern.
With all the work they're doing on durable workflows, hard to imagine that 2025 is anyone else's year.
https://moltar.github.io/typescript-runtime-type-benchmarks/
This feels about as trivial as an aggregate package of `isOdd` / `isArray` absurd micropackages. Surely I must be missing something because they're incredibly popular?
yeah i could do it manually, but the integration with other tools was the killer.
- Yes, it doesn't tree-shake well because of the chaining API. We accept this tradeoff because there's a lot of value coming from those kilobytes.
- In pure benchmarking numbers, it's nowhere near the fastest validator but I would wondering where you're using Zod and needing millions of operations per second. In my world, the network absolutely diminishes any performance benefits of the fastest validation library.
- It can slow down typescript type checking in extreme cases. This one is aimed at those folks that have a large number of very complex schemas. A good majority will not encounter this problem.
I say all this but on the flip side, I will pick Zod again and again because it has the biggest community behind and is well on its way to having ecosystem around e.g. with react-hook-form, trpc and other framework integrations. For most of my projects the trade-offs above don't materialize. Regarding all the performance and bundle size concerns, I've spoken to Colin, creator of Zod, on a couple of occasions about these and they're all getting addressed in Zod v4 which I'm raring to try out when it's available.
Though I admit another important aspect is community adoption. If your 3rd-party dependency uses zod internally, well now you’re bundling in both, and the added network latency probably negates any performance improvement you were getting in a web app. That’s why I wish libraries would use something more generic that allows you to dependency-inject what you’re already using, like https://github.com/decs/typeschema
Another feature that I use intensively is transforming the response to parse JSON into more complex data types, e.g. dates but also project-specific types. In some situations, I also need to serialize these data types back into JSON. This is where Zod lacks most for my use-case. I cannot easily specify bidirectional transforms, instead I need to define two schemas (one for parsing, one for serializing) and only change the transforms. I have added type assertions that should catch any mistakes in this manual process, but it'd be great if I didn't have to keep these two schemas in sync.
Another comment mentioned @effect/schema [0], which apparently supports these encode/decode relationships. I'm excited to try it out.
It makes tool calling and chaining very robust, despite how finicky LLMs can be.
Basically joi (https://joi.dev/api/?v=17.13.3) but different in some way?
Personally I use zod in my API for body validations, it's super nice to write the schema then just use `type Body = z.infer(schema)` to get the TS type to use inside the code.
The main distinction is that ZOD allows you to extract a TypeScript type from your schema. This means you get both compile-time and run-time type checking.
Typescript is build-time validation, but in the end TS is "just JS"
Zod provides runtime validation (and also works well with TS)
not really "instead", more like "in addition to". Even if your code compiles, if you are receiving data, e.g., via API, then you need to check that it actually conforms to the type/schema you expect. What is run is JS, so it, sadly, won't just crash/error if an object that is supposed to be of `type Cat = {name: string, ownerId: number}` lacks an `ownerId` at runtime.
Have you used Pydantic in Python? It's like that, but feels worse, IMO lol. I say this because Pydantic fits into writing Python code much more naturally than writing Zod stuff fits into writing TypeScript, IMO.
Why do you need to do `type User = z.infer<typeof User>;` instead of declaring a class with typed fields and, idk, deriving a parser for it somehow? (like you would with Serde in Rust for example). I don't understand why Zod creates something which looks like an orthogonal type hierarchy.
For context: I come from the backend land, I enjoy strong, static typing, but I have very little experience with JS/TS and structural typing
The schema object is useful for runtime validation, e.g. User.parse(). this is handy when validating payloads that come over the wire that might be untrusted. the output of the “parse()” function is an object of type User
you can kind of think of it like marshaling Json into a struct in Go :)
Serde in Rust does this with the Rust macro system, but TypeScript doesn't have a macro system. That's why people have to go the other way, the programmer defines the parser, then TypeScript can infer the type from the parser.
I have seen a library that invented their own macro system (a script that you configure to run before build, and it writes code into your node_modules directory), though I can't recall the name.
That’s mostly why I’m curious about the lack of mention :)
I wasn’t aware however of JSON Type Definitions, which hadn’t been invented last time I released software with Ajv, but it does appear to be able to reflect those as well as validate from them, so thank you for showing me that.
Feels like it’s worth that trade off to have a consistent experience consuming other APIs as well, but I could be wrong; I think so far I’ve only used it when I need to consume APIs rather than produce them.
Just to make it explicitly clear, I only received one email - reading my earlier comment back, it made it seem like there maybe was more. It could have definitely been worse!
Thinking maybe Zod + Zod open API.
Really looking to replicate similar spec first workflow similar to protobuf services.
https://typespec.io/ also looks promising but seems early.
If someone has tried both, can anyone share how it compares with tRPC[0]?
[0] https://trpc.io/
That being said, I am actually slowly migrating off ts-rest and adopting @effect/schema and @effect/platform/HttpApi, I foresee this being the direction the typescript ecosystem heads in over the next few years. However, the APIs are not stable yet and it has a bit of a learning curve, so would not adopt lightly
It also supports typespec using their transpilation to openapi 3 tooling
Well that's just blatantly not true. Which languages are you thinking of? I'm sure I'm misunderstanding what you said.
I can't think of a single server side language that doesn't have to parse external untyped objects. That's where these serialization libraries come into play.
For example, in Kotlin, you declare a data class and mark it as @Serializable and it generateds `toJSON/fromJSON` for you. IMO it's a much better experience than Zod.
That's what I said too.
> For example, in Kotlin, you declare a data class and mark it as @Serializable and it generateds `toJSON/fromJSON` for you. IMO it's a much better experience than Zod.
If the JSON object matches the data class exactly, the Zod parser and the Kotlin Serialization parser and Jackson and all those other JSON parsers are similar in complexity.
However, where Zod shines is if the JSON object doesn't match your domain class exactly, e.g. you want to parse a JSON number into a Date, or you want to parse a string field into some custom domain object. In those cases, in zod this is a one-liner with `.transform(...)`. Other libraries will require all kinds of weird workarounds to support this.
The other thing Zod does really well is composition, i.e. making new schemas out of existing schemas. Something like this is difficult to express in most language's parser frameworks:
const User = z.object({id: z.string(), username: z.string(), ...})
const CreateUserPayload = User.omit({id: true}) // Same as user, but without the id field
const UpdateUserPayload = CreateUserPayload.partial() // Same as CreateUserPayload, but now all the fields are optionalIn Java Object something = new Map(); String badCast = (Object) something; // This line would throw a ClassCastException because something is not a String
This has the advantage of throwing an exception in the correct place, instead of somewhere down the line.
Java - Jackson
Rust - serde
Python - marshmallow
etc
(Make sense, Go has arguably the largest stdlib of any language.)
The main goal of WebAssembly is to facilitate high-performance applications on web pages, but it is also designed to be usable in non-web environments.[7] It is an open standard[8][9] intended to support any language on any operating system,[10] and in practice many of the most popular languages already have at least some level of support.
Why not make it so typescript has options to compile to zod etc with a flag for runtime?
I seriously don't understand why I spend time on writing this as the fanbois who never tried anything nice that doesn't need this think it's the best thing. You all loved left pad and this is no different.