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?
Asked
Active
Viewed 570 times
4
-
I don't see `ostring` anywhere in the docs – Konrad Aug 10 '22 at 17:19
-
that's true, but when you using the latest version of zod, you can use it as an alternative for the z.optional() – Veewoo Aug 10 '22 at 17:21
2 Answers
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