Hacker News new | past | comments | ask | show | jobs | submit login

Could someone explain to me what problem exactly Zod solves?

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




> deriving a parser for it somehow

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.


There’s no macro system in TS that could analyze the type to build the parser. So, you work the other way and build the parser and then produce the type from that.


Zod offers runtime type validation where typescript only does this at build time. You can also use it for data normalization, safely parsing date strings to Date objects for example.


The “type User =“ statement creates a TypeScript type from the zod schema, which can be useful when passing that definition around to functions

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 :)


The User object in your example is used to parse the data. Its the “somehow” part of your question. There is no way to go from a type to data in typescript (there is no runtime awareness of types whatsoever) so zod solves this by you writing the zod object and then deriving the type from it. Basically you only have to weite one thing to get the parser and the type.


I used it to validate data from config files matched the schema. I imagine it could be useful for other sources of suppose-to-be-structured data like an http body.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: