Feature Request: Allow generating an object with a full set of defaults that may not validate
See original GitHub issueI am looking to use zod as a way to validate user configuration files for a command line utility. It looks like a great fit compared to what we are doing now, but I am having trouble with one aspect.
The workflow we use is:
- Allocate an initial set of defaults in a nested object (note: this isn’t fully filled in so won’t validate the schema)
- Pass to a user provided configuration function (ex. app.config.js) that extends the configuration
- Fill in final settings based upon combination of user and defaults
- Validate final config with schema. (looking for extra properties, validation checks, etc)
My problem is that in this model I don’t see a way to use zod to create the initial defaults object. I know I could create it as a plain old javascript object separate from the schema, but I was hoping to take advantage of the .default() methods within the schema to have the schema be self describing without having a separate large defaults object.
So my hope was to make something like this work:
const ConfigSchema = z.object({
/** The name to use. */
name: z.string().default('blah'),
/** Another nested part. */
nested: z
.object({
value: z.number(),
val2: z
.string()
.nullable()
.refine((v) => v && v.length === 5, 'Must be length 5.'),
})
.default({
value: 20,
val2: null,
}),
});
type ConfigType = z.infer<typeof ConfigSchema>;
describe('zod', () => {
it('validates a good value', () => {});
it('can provide defaults to override', () => {
// We can build a set of default values that don't validate yet
const default_results = ConfigSchema.safeParse({}); // <--- Need something here to just get defaults
const cfg = default_results.data;
expect(cfg.nested.val2).toEqual(null);
// then: user modifies it with config overrides
cfg.nested.val2 = '12345';
// and: now it can validate
const results = ConfigSchema.safeParse(cfg);
});
});
Is anything like this possible or practical as a feature in zod? I think it is effectively a SafeParse that doesn’t do any checks, but instead just sets the default values on the object passed in.
Issue Analytics
- State:
- Created 3 years ago
- Comments:7 (3 by maintainers)
Top GitHub Comments
@vriad That is brilliant!! Thank you so much for that idea. I think I have what I need to try it out.
I think we can close this out for now and I will work with this pattern.
Ran into one interesting issues. This pattern works to build up the schema, but the type of the schema returned by getSettingSchema includes the nullable. So if I try to infer the strict schema into a typescript type it still has the nulls involved.
I can probably still make this workable but would be great to find a way to infer the correct typescript type.