Describe the bug
When using a strict() object schema, fields with ensure() or default() behave unexpectedly for optional() fields.
To Reproduce
const yup = require("yup");
it("should pass", async () => {
const schema = yup
.object({
name: yup.string().optional().ensure(),
works: yup.boolean().optional().default(false),
})
.strict();
const obj = {
name: undefined,
works: undefined,
};
const validated = schema.validateSync(obj);
expect(validated.name).toBe("");
expect(validated.works).toBe(false);
});
https://codesandbox.io/p/devbox/relaxed-joji-n5mrnl?workspaceId=ws_Dp52T8Q7znsra3EKyyiAcV
Note that in this case the type interference of the schema is also incorrect. validated is shown to have the type { name: string, works: boolean }, but because it’s strict() the values can actually be undefined!
Expected behavior
I feel this is a major gotcha in how yup works. The strict() modifier gives optional() precedence over ensure() and default() which is highly unexpected. Given that the typing also does not match reality in this case, I’m assuming this is not intentional behavior.
In strict() schemas, ensure() and default() should still work on optional() fields.
Describe the bug
When using a
strict()object schema, fields withensure()ordefault()behave unexpectedly foroptional()fields.To Reproduce
https://codesandbox.io/p/devbox/relaxed-joji-n5mrnl?workspaceId=ws_Dp52T8Q7znsra3EKyyiAcV
Note that in this case the type interference of the schema is also incorrect.
validatedis shown to have the type{ name: string, works: boolean }, but because it’sstrict()the values can actually beundefined!Expected behavior
I feel this is a major gotcha in how
yupworks. Thestrict()modifier givesoptional()precedence overensure()anddefault()which is highly unexpected. Given that the typing also does not match reality in this case, I’m assuming this is not intentional behavior.In
strict()schemas,ensure()anddefault()should still work onoptional()fields.