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)
Zod (including Zod 4) does not support this particular flavor of exactness.
In Zod 4, Zod will differentiate between these two:
This is intentional. I could have implemented it such that
type Aabove is{ prop?: string }, but that would have been inaccurate/wrong.The
Aschema will absolutely return{ prop: undefined }if that’s what you pass into it. Changing this behavior (such that an optional property does not accept theundefinedliteral 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
exactOptionalPropertyTypessetting 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 requestz.strictExactObjectandz.looseExactObjectvariants…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 totrue.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/bunexists 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
This is particularly annoying when using
drizzle-zod, as things like: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
exactOptionalPropertyTypesaltogether 🤣):@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:
The parse call above issues the following compiler error:
This is because the schema accepts a present,
undefineddescription while myEntitytype 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
partialordeepPartialto 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
partialanddeepPartialas well.Unfortunately I’m not aware of a workaround at this moment.
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 acceptundefined.Another possibility is to add an
optionalKeysparameter toz.objectso:I think is better this way, as
dbeing present or not is an attribute of thedkey inside the object type, not of the type of thedvalue.Or would there be consideration of
.optional()taking an options object to change the behavior?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.objectsupport theproperty?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
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:
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
addQuestionMarksandbaseObjectOutputTypeand infer Required Key withextends ZodOptional) the core of the problem is that ZodOptional adds|undefinedto its in and output.Removing that assumption breaks other tests because optional can’t depend on its wrapping context.
E.g. here
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?