by agluszak · 2y ago · 0 comments
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
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.
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 :)