It'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).
It'd be nice to have zod help the developer max out their chances of parsing a valid object, when it's manually constructed. Example:
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
Where the expected input type was
Input(from theZodType<Output, Def, Input>) rather thanunknown. So the above code would error because the developer usedbirthdateinstead ofage.This would be especially useful for types with a custom
.refineor.regexmethod or similar where it could be misleading to use just a type declaration:The above will compile, and implies that the
const useris a validatedUserinstance, but it isn't becausenamedoesn'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).