Content
- Content
- Introduction
- Understanding the why
- Managing contracts
- Traditional approach
- The Zod Way
Simple example
- Defining the Zod schema
- Convert Zod schema into Typescript types
- Create some pizzas
- Run-time validations
- Establishing a new standard - End-to-end Typesafety
- Striking the right balance
- Conclusion
Introduction
I recently came across a neat little library called Zod.
My first reaction looking through the documentation was this looks interesting.
It wasn’t until I tried it that I felt the difference — The difference is MASSIVE.
Nothing comes close to it.
It’s a different approach but once you try out Zod, I think you would know what I mean.
In my opinion, Zod’s approach hits the right balance between robust code, and developer experience (DX) when working with data validation in Typescript.
⚠️ Disclaimer: After reading this article, you may not want to use any other validation library! (You’ve been warned)
Understanding the why
Typescript introduces great checks during development by statically checking the code meets the “contract” defined in the types.
This works for most cases, however, in production, it becomes more complex.
By establishing a contract it forces us to narrow the scope of the inputs and outputs.
In essence, you reduce the surface area hence making the function more predictable.
Now comes the question, how is this done in Javascript ?
Traditional approach
The traditional approach to achieve this is installing some sort of validation library (ie Joi, Ajv etc).
The most common application for this is managing form inputs with user input data.
However, it doesn’t have to be only for forms, you can use run-time validation for anything.
It will make your code more robust because any sort of data not meeting a contract will be considered a failure.
There is not in between or edge cases. It makes the code very strict.
Well, is there a better way ?
What if I told you there is...
You can probably guess it. I’ll give you a hint, it start with a Z.
The Zod Way
Enter Zod.
Here is where Zod differs from all the other validation libraries.
How is it different from everything else ? Zod takes a schema first approach.
Meaning, you start with your validation schema (Zod schema).
Then, this Zod schema becomes your validations, and your types.
So, you get the best of both worlds!
Not only do you you get run-time validations from the schema but you also get the types by converting the schema into Typescript.
And... that’s all for now, stay tuned for more!
If you found this helpful or learned something new, please do share this article with a friend or co-worker 🙏❤️ (Thanks!)
Also published at - jerrychang.ca
⚠️ Note:
Yup also supports the ability to infer types from the data schema defined.
You can do something like yup.InferType in order to get your Typescript type.
Just throwing it out there as another great library that allows you to do similar things as Zod.
SOCIAL SHARE CARD GENERATOR