【问题标题】:How get values inside min(), max() in zod?How get values inside min(), max() in zod?
【发布时间】:2022-12-27 23:23:22
【问题描述】:

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

【问题讨论】:

    标签: reactjs typescript zod


    【解决方案1】:

    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);
    

    【讨论】:

    • This is awesome! Zod is awesome!
    猜你喜欢
    • 2022-11-20
    • 2022-12-02
    • 2022-12-26
    • 2022-12-01
    • 2022-12-02
    • 2022-12-27
    • 2022-12-01
    • 2022-12-02
    • 1970-01-01
    相关资源
    最近更新 更多