Hacker News new | ask | show | jobs
by bluepnume 620 days ago
You find it weird that a type system doesn't do runtime validation? Is that common in many other languages?
2 comments

Well in most statically typed languages with a VM (Java/C#), there's some sort of runtime validation

In 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.

Other statically-typed languages do have to deal with the problem of parsing external objects. In my experience, none of them have parsers as good as Zod in terms of ergonomics.
> Other statically-typed languages do have to deal with the problem of parsing external objects.

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.

> I can't think of a single server side language that doesn't have to parse external untyped objects.

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 optional