zod: optional should not add undefined to type signature

I’m sorry if this is a duplicate, I could not find an existing issue or discussion that seemed to be exactly about the following. It’s really rather simple: the following schema infers the wrong type

const schema = z.object({
  foo: z.string().optional()
});

is inferred as

type Schema = {
  foo?: string | undefined
};

when it should really be

type Schema = {
  foo?: string
}

Let me showcase the issue with two different typescript playgrounds. They both have the same content, but the second has exactOptionalPropertyTypes enabled.

exactOptionalPropertyTypes: false

This playground errors, because even though we know that foo exists on result the compiler adds undefined to the set of possible types for result.foo.

exactOptionalPropertyTypes: true

And here we eliminated the error, because the compiler knows that if foo exists on result it must be exactly a string.

The problem to note here is that the decision to include undefined should be up to the compiler. Zod takes that decision away and subsequently makes it impossible to truly express optional keys.

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 27
  • Comments: 41 (3 by maintainers)

Most upvoted comments

Zod (including Zod 4) does not support this particular flavor of exactness.

In Zod 4, Zod will differentiate between these two:

const A = z.object({ prop: z.string().optional() });
type A = z.infer<typeof A>;
// => { prop?: string | undefined; }

const B = z.object({ prop: z.string().or(z.undefined()) });
type B = z.infer<typeof B>;
// => { prop: string | undefined; }

This is intentional. I could have implemented it such that type A above is { prop?: string }, but that would have been inaccurate/wrong.

The A schema will absolutely return { prop: undefined } if that’s what you pass into it. Changing this behavior (such that an optional property does not accept the undefined literal by default) would be a catastrophically breaking change. Every Zod users would need to add .or(z.undefined()) to every optional property. As a default behavior, this would be absurdly user-hostile. It’s a no-go.

So given that an “exact” runtime behavior isn’t viable, the static domain reflects this and always adds | undefined.


It’s actually technically possible for Zod to statically detect the exactOptionalPropertyTypes setting and use different return types conditional on that. But it isn’t possible for Zod to read this value at runtime (obviously Zod doesn’t have access to your tsconfig.json at runtime) so there would’ve needed to be a separate mechanism for configuring “exact optionality” (eg. z.config({ exactOptionals: true })). But this a) adds complexity and b) introduces the possibility for misconfiguration & disagreement between runtime and static behavior—and that’s exactly the kind of problem Zod exists to prevent.

I considered a z.exactObject() API but then people would immediately request z.strictExactObject and z.looseExactObject variants…no thank you. That level of API bloat isn’t worth it for what is ultimately a very niche feature.

yeah? The default is false; that doesn’t make it any more correct for zod to take away the decision from the compiler for those that have it set to true.

Imho this isn’t an enhancement but a bug - zod “deliberately” add’s implicit nullability even if that nullability is explicitly forbidden. From what I’m reading from other issues in this repo I’m fairly certain that this is not what zod wanted or intended.


fyi: @types/bun exists by now, just in case.

This will be implemented in Zod 4 (currently in beta). See the announcement.

I found a work arround in whitch you can make it a nullable too and when the type is infered the null is added as a type incase thats what you nedded

profileImage: z.string().optional().nullable(),

This is particularly annoying when using drizzle-zod, as things like:

const patchUserSchema = createInsertSchema(user).omit({ id: true }).partial()

will result in types that are incompatible with drizzle itself. (The same happens when extending with .optional())

Here’s the workaround we had been using for some time (before disabling exactOptionalPropertyTypes altogether 🤣):

type RemoveUndefined<T> = {
  [K in keyof T]: Exclude<T[K], undefined>
}

export const removeUndefinedProps = <T extends object>(obj: T) => {
  return Object.entries(obj).reduce((acc, [key, value]) => {
    if (value !== undefined) acc[key as keyof T] = value
    return acc
  }, {} as RemoveUndefined<T>)
}

// ... later in the schema definition

const patchUserSchema = createInsertSchema(user)
  .omit({ id: true })
  .partial()
  .transform(removeUndefinedProps)

@colinhacks nothing seems to be working. and is there any source code docs. and there is no comment / docs in the codebase!!! 👎🏻

No, this still isn’t possible.

I have been bitten by this problem recently. Here’s a simplified version of the use case I have:

type Entity = {
  name: string;
  description?: string;
};

const EntityCreationRequest = z.object({
  name: z.string(),
  description: z.string().optional(),
});

const entity: Entity = EntityCreationRequest.parse({
    name: "hi there",
});

The parse call above issues the following compiler error:

'entity' is declared but its value is never read.typescript(6133)
Type '{ name: string; description?: string | undefined; }' is not assignable to type 'Entity' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties.
  Types of property 'description' are incompatible.
    Type 'string | undefined' is not assignable to type 'string'.
      Type 'undefined' is not assignable to type 'string'.typescript(2375)

This is because the schema accepts a present, undefined description while my Entity type doesn’t.

On one hand, Zod’s notion of optionality belongs to the schema of the value itself, whereas the optionality in typescript is in the relationship between an object key and a value, so the current behavior doesn’t seem completely wrong to me in this specific case, but it does feel wrong when applying partial or deepPartial to an object schema.

I guess the only non-breaking fix would be to introduce a new type of optionality, attached to the object key itself and have that behave differently, which would probably require changes to partial and deepPartial as well.

Unfortunately I’m not aware of a workaround at this moment.

Or would there be consideration of .optional() taking an options object to change the behavior?

.optional({ exact: true })

Sorry to add to this issue, but I don’t think @darcyrush’s suggestion was addressed in this comment. .optional({ exact: true }) looks like a good to solution to define an optional key that doesn’t accept undefined.

Another possibility is to add an optionalKeys parameter to z.object so:

const schema = z.object({
  d: z.string(), // d?: string
}, { optionalKeys : ['d'] });

I think is better this way, as d being present or not is an attribute of the d key inside the object type, not of the type of the d value.

Or would there be consideration of .optional() taking an options object to change the behavior?

.optional({ exact: true })

I empathize with the desire to delete 3k LoC from a project maintained in peoples own free time, but we use Zod for type safety and currently we have to relax all our projects TS settings specifically due to this single bug.

I would rather have type safe code with poor DX than the other way around.

This was my primary use case for .interface, will .object support the property? syntax?

@TahsinAyman it’s their prerogative not to consider this issue and they’re under no obligation to write the codebase in any other way than it is now.

Honestly, if zod were my project I’d close this issue since

  1. considering the current structure and maturity of this project it just doesn’t make sense to introduce a breaking change for an edge case (even though it’s a valid case)
  2. fixing it without introducing a breaking change to the api would require an enormous rewrite

If people then started to complain about how my codebase doesn’t cater to somebody elses taste I’d be less than willing to see their point.

For me it just meant sticking closer to FP patterns and using it like this:

z.object({
  foo: z.string().optional().transform(option.fromNullable)
})

the more I look at this, the more it looks like this won’t be possible without a breaking change. While I did get correct optional inference working (basically just switch addQuestionMarks and baseObjectOutputType and infer Required Key with extends ZodOptional) the core of the problem is that ZodOptional adds |undefined to its in and output.

Removing that assumption breaks other tests because optional can’t depend on its wrapping context.

E.g. here

const stringSchema = z.string().optional();

const objectSchema = z.object({
  foo: stringSchema
});

type S = z.infer<typeof stringSchema> // expectation: string | undefined
type O = z.infer<typeof objectSchema> // expectation: { foo?: string }

Since the stringschema can’t know when it’s being used in an object context it’s impossible to correctly represent optional keys without also making the value “undefinedable”.

Imho the only true solution (and maybe even the right one) would be to strictly reserve .optional() for usage within objects and to have a new operation like .nullable(), e.g. .orUndefined() for everything else.

@colinhacks , sorry for directly mentioning you but do you see any other solution?