colinhacks / zod

TypeScript-first schema validation with static type inference
https://zod.dev
MIT License
33.92k stars 1.18k forks source link

Question: How to extend/copy array schema but only change the containing type #3726

Open brupxxxlgroup opened 2 months ago

brupxxxlgroup commented 2 months ago

Hello

I have a question regarding arrays.

Given following simple example

const myObjSchema = z.object({
  name: z.string(),
});

const arrayOfMyObj = z.array(myObjSchema).min(1).max(2);

What i wanna do is kind of changing the containing type of the array like this.

const arrayOfMyObjExt = arrayOfMyObj.changeType(myObjSchema.extend({ foo:z.string()}));

but i want to keep the constraints of min and max of the original array.

Why do i need this?

I want to extend and existing schema with some OpenAPI documentation and i do not have access to the original schema definitions. I want to keep as much from the original schema as possible to not run out of sync. For z.object i can use extends but there is nothing like this for z.array.

Any hints?

Thank you so much for help.

sunnylost commented 2 months ago

Maybe you can try something like this:

const arrayOfMyObj = z.array(myObjSchema).min(1).max(2);

const newSchema = arrayOfMyObj.and(
  z.array(
    z.object({
      foo: z.string(),
    })
  )
);

Transforms original schema into an Intersection type.