✨ 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().
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.
⭐ 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:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Substack: https://nhannguyendevjs.substack.com/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/
Top comments (0)