profile
viewpoint

Ask questionsRFC: Make object schemas nonstrict by default

Zod's policy of disallowing any unknown keys by default is confusing and probably not worth it. It also makes the inferred types incorrect:

const A = z.object({
  a: z.string(),
});

const B = z.object({
  b: z.string(),
});

const AB = z.intersection(A, B);


type AB = z.infer<typeof Teacher>;
// { a: string; b: string };

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!

vriad/zod

Answer questions chrbala

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' }
useful!

Related questions

No questions were found.
source:https://uonfu.com/
Github User Rank List