In our previous post, we discussed how we can use User defined type guards and their advantages.
In this post, i'd like to show the same concept but with a popular typescript library called Zod. Zod is a very powerful library that gives runtime safety to applications written in typescript.
Lets start by looking at an example of user guard written in plain typescript.
So lets break it down as to what is happening:
- We have a user interface with 3 string properties and 1 boolean.
- We have a type guard that validates if an object passed is a typeof User.
- The type guard is checking each mandatory fields.
So i can already think of few issues with the type guard.
- We could just validate a property against its primitive type, e.g.
typeof obj.email === 'string'
and we can pass any value. - We can pass any valid string to the uuid but is it really a uuid ?
- Same can be said about the email, we can pass any valid string and it'll satisfy the guard.
- We could also add mandatory properties to the user interface later and completely forget to add them to the type guard.
Now lets rewrite the above but this time using Zod
Zod allows you to write your schemas for objects and its validations in the same place. e.g. uuid and email are defined as
uuid: z.string().uuid()
email: z.string().email()
Not only is it much cleaner, less code and more useful, it also future proofs the code as we can add more properties to the schema without needing to update the type guard.
Please checkout Zod library as to me, it is one of the must have in your codebase if you care about runtime stability and experience of your applications.
Until next time, happy Zoding!
PS: You can find the code in the Gist here
Top comments (0)