Search code examples
zod

How to explicitly skip checking part of the schema in zod


I would like to understand if and how it is possible to skip validating parts of a schema in zod?

In the following example, I would like to validate the foo schema to make sure that the object contains a property id of type number and a property data of type array but (maybe cause there is a lot of data) I would like to prevent validating all the actual array entries in data.

import {z} from 'zod';

const foo = z.object({
   id: z.number(),
   data: z.array(z.string()),
});

Solution

  • This does the job:

    const dataItem = z.custom<DataItem>(); // type DataItem defined by you elsewhere
    const foo = z.object({
           id: z.number(),
           data: z.array(dataItem),
        });
    // { id: string; data: DataItem[] }
    
    

    https://github.com/colinhacks/zod/discussions/1575