`parse.typed(...)` or some kind of typed parse method
See original GitHub issueIt’d be nice to have zod help the developer max out their chances of parsing a valid object, when it’s manually constructed. Example:
const User = z.object({
name: z.string().regex(/^\w+ \w+$/),
age: z.number(),
})
User.parse({
name: 'Bob',
birthdate: new Date('1970-01-01'),
})
The above code compiles, but we have enough information to know that it’ll throw a ZodError at runtime. It’d be nice if there was a method like
User.parse.typed({
name: 'Bob',
birthdate: new Date('1970-01-01'),
})
Where the expected input type was Input
(from the ZodType<Output, Def, Input>
) rather than unknown
. So the above code would error because the developer used birthdate
instead of age
.
This would be especially useful for types with a custom .refine
or .regex
method or similar where it could be misleading to use just a type declaration:
const user: z.infer<typeof User> = {
name: "Robert'; -- DROP TABLE Students; --"
age: 40,
}
The above will compile, and implies that the const user
is a validated User
instance, but it isn’t because name
doesn’t match the regex. The current options are to do the above, which is safe-looking at compile time, but unsafe at runtime, or to use .parse(...)
which is unsafe at compile time and safe-ish at runtime (but will throw errors).
Issue Analytics
- State:
- Created 9 months ago
- Comments:5 (2 by maintainers)
Top GitHub Comments
I don’t think that this will ever be added to Zod, because it’s my understanding that parse is meant to take something that is unknown and turn it into something that is known at compile time. So when you are trying to parse an object that is statically in the code base, that’s something that is already known at compile time. In example code we do this all the time for learning/teaching purposes, but I don’t know that I have ever done that in a real app. In real apps I use Zod for checking user input or a response from an api, which are things that can’t be known at compile time. I hope this makes sense. Please let me know if you have questions or if I am misunderstanding what you are talking about.
Yes it’s a slightly different use case than validating API inputs, and I usually want this when using refinement types, or regex strings, or similar, which perform runtime validation which is not reflected at compile time. And yes that helper function does the trick for most cases - what I’m asking is whether it could become part of zod. There are some edge cases like .transform types with a different input typearg which it’d be sensible to solve in one official place.