Skip to content

exactOptional() returns same type as optional() (does not exclude explicit undefined) #5615

@Fl4wless

Description

@Fl4wless

Describe the Bug
I am referring to the changes introduced in PR #5589 regarding .exactOptional().

My understanding is that .exactOptional() should distinguish between a missing key and a key explicitly set to undefined. However, currently, it appears to generate the exact same type as .optional(), allowing explicit undefined values or inferring the type as T | undefined instead of just optional T.

Steps to Reproduce

  1. Define a schema using .exactOptional() alongside one using .optional().
  2. Inspect the inferred types or try to parse an object with explicit undefined.
import { z } from "zod";

const schema = z.object({
  a: z.string().optional(),
  b: z.string().exactOptional(),
});

type SchemaType = z.infer<typeof schema>;

// => {
//   a?: string | undefined;
//   b?: string | undefined;;
// }

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