Search code examples
javascriptzod

What is the difference between z.optional(z.string()) and z.ostring() of zod?


To make any schema optional, I've seen that zod provides two methods: z.optional(z.string()) and z.ostring(). I wonder what is the difference between them? And what should I use for most cases?


Solution

  • Looking at the source code reveals that:

    const ostring = () => stringType().optional();
    

    And from the readme we know that:

    const optionalString = z.string().optional(); // string | undefined
    
    // equivalent to
    z.optional(z.string());
    

    So there is no difference