Search code examples
reactjstypescriptzod

How get values inside min(), max() in zod?


I have the following schema.

const schema = z.object({
 name: z.string().min(1)
})

Is there any way in zod to get the value stored in min?

const minValue = schema.shape...? // should be 1

Solution

  • Yes, after a little poking around, there's a hidden _def field that you probably need to //@ts-ignore:

    const minValue = schema.shape.name._def.checks[0].value;
    

    If you have more than one check, you can find the one you want:

    const minValue = schema.shape.name._def.checks.find(({ kind }) => kind === "min").value;
    

    Note that find will return undefined if no such check was found.


    But may I interest you in an alternative?

    const nameMinLength = 1;
    
    const schema = z.object({
     name: z.string().min(nameMinLength)
    });
    
    // now you already have it
    console.log(nameMinLength);