Skip to content

.optional() and --exactOptionalPropertyTypes #635

@bwbuchanan

Description

@bwbuchanan

Currently, .optional() behaves like:

const user = z.object({
  username: z.string().optional(),
});
type C = z.infer<typeof C>; // { username?: string | undefined };

This results in a type mismatch when you're using --exactOptionalPropertyTypes in TypeScript 4.4 and expecting type C to match an interface definition like:

interface User {
  username?: string;
}

.partial(), .partialBy(), .deepPartial() all have the same issue.

It would be nice to unbundle the optionality of the key from the union type with undefined for the value.

I suggest that these methods be changed to specify the optional absence of the key by default, and perhaps accept an option to restore the old behavior of adding .or(z.undefined()) to the value schema(s). This would unfortunately be a breaking change, but it makes more sense than the current behavior, especially as more projects adopt --exactOptionalPropertyTypes.

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