Strip unknown keys from object schemas by default
See original GitHub issueHi!
First of all, looks like a great job you did with this library. Looks very clean and developer friendly, and has some features I’m missing from io-ts.
Actually, I extended io-ts with some of them your library offers out of the box, but before I would jumping into and trying whether your library would work in my project, I’d like to ask something in advance to see if I could achieve it with it:
Is there a way to ‘export’ a structure (object) that way Zod would delete the keys that are masked out (with omit
)?
The use case: I’d like to use Zod to serialize (‘export’) and unserialize (parse) custom structures (actually React component states, but could happen for multiple other use cases). But sometimes, there are data in the component state which is needed for runtime, but not needed (and I don’t want) to serialize/unserialize.
At unserialization, masking is OK, it will ignore the not needed ones if I create a new ‘masked’ type. But at serialization… I have the full data structure, and if I serialize it, it would contain all, even masked data as well. That’s what I don’t want.
An example based on a doc example:
const Recipe = z.object({
id: z.string(),
name: z.string(),
ingredients: z.array(z.string()),
});
const NoIDRecipe = Recipe.omit({ id: true });
type NoIDRecipe = z.infer<typeof NoIDRecipe>;
const data: Recipe = { id: 1, name: 'test', ingredients: ['x', 'y', 'z'] };
const serializable = NoIDRecipe.<serialize/export/clean?>(data);
Here, I’d like to make a copy of the ‘data’ variable, but with the NoIDRecipe schema, and in the copy (serializable) structure I want the ‘id’ keys to be removed, based on the schema (as NoIDRecipe doesn’t contain it). Is it possible somehow?
Issue Analytics
- State:
- Created 3 years ago
- Comments:6 (4 by maintainers)
Top GitHub Comments
Zod 2 is now in beta and strips all unknown keys by default!
@dexx086 @johannessjoberg
Looking forward to this feature as an avid
joi
user 🙌Is there a timeline regarding this?