Declare Lack of Value in zod (optional, nullable and nullish)

In this lesson we discuss how Zod works with TypeScript to handle special types like undefined, null, any, unknown, never and void.

We modify our room booking schema to demonstrate the use of optional and nullable Zod utilities.

By using .optional, we allow a property to be either its original type or undefined. With .nullable, we allow it to be either its original type or null. Finally, .nullish allows a value to be either its original type, null, or undefined.

For all cases, we run tests to show how these schemas work in practice, as well as how TypeScript infers types.

Share with a coworker

Transcript

[00:00] Zod's schemas are trying to reflect the way the TypeScript compiler works as much as possible So it needs to provide some special schemas that reflect the TypeScript's internal types such as the undefined, null, void, any unknown and never. Now, let's take a look how this file is going to be run against ts-node and we will see that certainly undefined matches undefined, null matches null, undefined matches void, any possible value matches any schema, and any possible value matches unknown schema. Now if I uncomment the never schema, which is going to be matched against any value, a string In this case, this is going to throw the same way as TypeScript would not allow just any value or a string in this case against never since never is just an empty type which has no proper values. Zot also provides some special schemas on top of these undefined, null and etc. So let's modify our room booking schema and in due date we're going to pass the optional which is going to make that it's either what we've had before or undefined or certainly this one could not exist at all.

[01:26] So here we're going to pass the nullable which means that either this is the value that we've had before or null and finally we've got the nullish which could be either the value or undefined or finally null itself. So after saving the file Let's run it back again and I'm going to comment out the never one. So we will see that there is no error at this point. So here it's possible to pass undefined. So let's just make sure that this one is correct.

[02:01] Here we can pass null since this is nullable and here we can also pass null. So let's make sure that this one is also passing. But if this allows only the value itself and undefined and we pass null which is certainly beyond the allowed range of values then this is going to throw since this is expected string received null actually it should say expected string or undefined and received null. Still what you're going to use quite often is the optional, nullable or nullish