Search code examples
javascripttypescriptvalidationzod

How to Extend a Zod Object with Another Object and Pick Certain Entries?


I'm using Zod, a TypeScript schema validation library, to validate objects in my application. I have a scenario where I need to validate an object with nested properties and extend it with another object while picking only certain entries from the second object.

Here's what I'm trying to achieve:

logValidation.pick({
        level: true,
        event: true,
        userId: true,
        ipAddress: true,
        statusCode: true,
}).extend(validation.pick({
    limit: true,
    offset: true
}))

In the above code:

logValidation represents the schema for validating log objects.

  • I want to extend logValidation with another object containing pagination parameters (limit and offset).
  • However, I want to pick only limit and offset from the second object to extend logValidation.

But this code doesn't work as expected. Zod's extend method doesn't seem to support picking certain entries from the extending object.

Is there a way to achieve this functionality with Zod? I


Solution

  • You're using extend (which expects you to give it an object of properties, and will make a schema) when you should be using merge (which expects to to give it a schema).

    See https://github.com/colinhacks/zod?tab=readme-ov-file#extend