DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

Zod - TypeScript-first schema declaration and validation library #2

Image description

Runtime Type Checking with Zod

TypeScript is useful for checking the types of our variables at the type level.

However, we can not always be sure about what type of variables we will get from external sources like API endpoints or form inputs.

Zod lets us work around this by checking types at the runtime level as well as the type level, making it a useful library to add to your repertoire.

Example: Create a numberParser

We will create a numberParser by invoking z.number().

Image description

This creates something called z.ZodNumber, which provides several helpful methods.

Passing data into numberParser.parse() will error if it is not a number.

This means that any variable we create by calling numberParser.parse() will be typed as a number.

Image description

⭐ Experiment with Different Types ⭐

Zod allows us to use this same technique with other types as well.

For example, if we wanted to accept a boolean instead, then we could update our numberParser to z.boolean().

This technique with Zod gives us a solid base to build up from.


I hope you found it useful. Thanks for reading. 🙏
Let's get connected! You can find me on:

Top comments (0)