Skip to content

Regression in type inference for a union of array types inside an object type #2203

Closed
@daitay4

Description

@daitay4

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 (4d016b7#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.

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