typescriptzod

Schema to match an array with a string and an array


Given the following value:

['foo', ['bar', 'baz']]

I'm trying to use Zod to verify this schema:

z.array(z.string().and(z.array(z.string())))

However, Zod returns 2 errors:

Expected array, received string
Expected string, received array

Is it possible to achieve this schema validation with Zod?


Solution

  • The TL;DR is that and is giving you an intersection type: string & string[] which represents the overlapping properties between string and string[] (which are not many).

    Your data has a union of the types string | string[] so you would use .or instead. The value is either a string or a string[] but not both.

    z.array(z.string().or(z.array(z.string())))