-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
RFC: Make object schemas nonstrict by default #106
Comments
If object schemas become nonstrict by default (which generally makes sense to me), how would parsing work? I see some advantages in being able to give an object with extra keys, then parsing removes them. const Obj = z.object({
key: z.string(),
});
Obj.parse({key: 'value', key2: 'value2'}) // could return { key: 'value' } |
As mentioned in the doc,
I'm not sure if I'm missing anything here, but wouldn't this make the It also feels more confusing for Also it seems that in TypeScript,
So the inferred type ( type A = {
a: string;
}
type B = {
b: string;
}
type AB = A & B;
// Valid
const value: AB = {
a: "a string",
b: "another string",
}
It seems that currently const AB = z.intersection(A, B);
AB.parse({
a: "a string",
b: "another string",
}); which should be valid (based on TypeScript's definition of intersection) shows the error
I kind of feel like this is what should be fixed (instead of making object schemas nonstrict by default) so that the intersection works as expected (as in TypeScript)? |
The primary thing I care about regarding this issue is that there's a path to getting a clean object without erroneous keys. If you use zod to validate before a schemaless database, you might find out you have a bunch of unwanted fields if there aren't good protections in place. Perhaps making this explicit like a Even right now, this is a bit cumbersome because unused fields have to be manually removed. A value cleaner would make this nicer. |
value cleaner will be a gamechanger. |
Zod 2 is now in beta and it strips unknown keys by default. It alsso introduces methods for passing through unknown keys ( @chrbala @grreeenn @pkerschbaum @agentlewis @DogPawHat @eh-am @ryardley |
@colinhacks is this behavior still in place in v3? upd: sorry for a stupid question; yes, it is |
Zod's policy of disallowing any unknown keys by default is confusing and probably not worth it. It also makes the inferred types incorrect:
The actual inferred type here should be never because no data will properly pass validation.
If anyone has a reason why object schemas should be strict by default, speak now!
The text was updated successfully, but these errors were encountered: