4

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?

Veewoo
  • 65
  • 4

2 Answers2

3

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

Konrad
  • 21,590
  • 4
  • 28
  • 64
2

The two ways are the same.

z.ostring() and the like are shortcuts. They are equivalent in function to wrapping the normal type with z.optional() or chaining .optional(). In fact, they are implemented internally using the chained .optional().

Darryl Noakes
  • 2,207
  • 1
  • 9
  • 27