I understand that the point of zod is to parse untrusted input data and assert that it's of a type that matches your schema.
But usually that data is coming in via web APIs that guarantee at least its top-level shape, like string
or object
.
It seems like it would make sense for zod to do this top-level type checking on parse()
, if only to prevent silly mistakes like typos. But, seemingly, it doesn't.
As a simplified example to illustrate
const schema = z.string().email();
schema.parse(1); // no type error here - why?
It seems like parse(1)
should have a compile time type error, because we know it's impossible that the literal number
1 would validate correctly at runtime. We can't do that with some random string
input - the runtime parsing to ensure it's a valid email is required - but a number here seems like obvious programmer error and should not even compile.
A more practical example, which led me to ask this question
async function validateRequest(request: Request) {
const someSchema = z.object({ ... })
return someSchema.parse(request.json()) // didn't await request.json() so won't work
}
A silly mistake like omitting the await
above, seems like it should be easy to catch by someSchema.parse()
checking that I pass it an object
, not a Promise<object>
.
So, is there a way to enable this top-level type checking with zod?
Or is this behaviour intentional for some reason I haven't understood about zod's design?