zod: Regression in type inference for a union of array types inside an object type
I have some schema like the following:
z.object({
arrayProp: z.union([z.string().array(), z.number().array()]),
}),
this used to produce the following type for the arrayProp key: string[] | number[].
since version 3.21.2 this produces the following type:
string[] | (string[] & number[]) | (string[] & undefined) | (number[] & string[]) | number[] | (number[] & undefined)
this in turn causes many problems when trying to work with arrayProp, for example if I try to use an array predicate like map, I’m getting the following error:
TS2349: This expression is not callable. Each member of the union type '(<U>(callbackfn: (value: string, index: number, array: string[]) => U, thisArg?: any) => U[]) | (<U>(callbackfn: (value: number, index: number, array: number[]) => U, thisArg?: any) => U[]) | ((<U>(callbackfn: (value: string, index: number, array: string[]) => U, thisArg?: any) => U[]) & (<U>(callbackfn: (value: num...' has signatures, but none of those signatures are compatible with each other.
However, if I remove the wrapper z.object and use the following schema: z.union([z.string().array(), z.number().array()]) then I’m getting the correct type inference of string[] | number[]
Looking at the code for the 3.21.2 PR (https://github.com/colinhacks/zod/commit/4d016b772b79d566bfa2a0c2fc5bfbd92b776982#diff-a5a27c41f819170124f4fd4cf24b1d71b8ab2966a4bde235a7f8db53dc8ef486) suggests that this has to do with changes made to the internalDeepPartial type.
For now we’re sticking with 3.21.1 version, but I would be happy to see that fixed as we use this pattern on multiple occasions across our project.
About this issue
- Original URL
- State: closed
- Created 4 years ago
- Reactions: 22
- Comments: 17
Simpler one:
foois inferred as the expected type, whilebarisn’t.Closing this issue as it seems to have been resolved, perhaps via #3352 as noted by @homemade-ramen
I can confirm that my above posted issue was resolved with the most recent version.
Any updates?
Stumbled upon this in latest version 3.22.4 https://www.typescriptlang.org/play#code/JYWwDg9gTgLgBAbzgLzgXzgMyhEcDkyEAJvgFBkDGEAdgM7wCuNwtcAvCgHTOs0AUAbWRcGUYDQDm-AJRcAhlCjyAnrIA0ImoxAAjAKZRZCpatkBdGRRgqw+rABt5MAPo27HbhMyGAPO-0ITDheWgA+MgB6SLhYgD0AfgpqengafQZ9Yhc6SgALfRB5TxEIXQArfUoYfiRQmnQrMgC4dMzsls4Rbz8AoNaMmCyc-ML5MMF8evxzKJj4pKA
I face something similar:
It appears that this problem may be fixed in the latest version (v3.23.0 and up). The potential fix is included in https://github.com/colinhacks/zod/pull/3352
You can check if the issue is fixed in the TypeScript Playground.
Additionally, https://github.com/colinhacks/zod/issues/2325 can also be fixed with the same fix.
@colinhacks, could you please review this and confirm that the issues have been resolved?