Skip to content

Unexpected behavior and incorrect typing when combining optional()+ ensure() / default() with strict() #2309

@eelco

Description

@eelco

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions