TypeScript gives you a secret weapon for fighting errors in your code by checking all of your types at build-time within your application, but what happens at runtime when you receive un-typed data from an external source?
An external source might include JSON from an API or even user input from a form.
When you get untyped runtime data, you can still confidently check its type, but to do that, you need to create a schema and parse the untyped data against the schema.
Thankfully, there are several libraries built specifically to help us with this.
We will be comparing several of them below, but if you'd like to skip to the end, we highly recommend Zod for it's completeness and ease of use.
If you'd like to understand more in depth why Zod is the top choice, its author Colin McDonnell has an essay that explores why he decided to write Zod in the first place.
The declarative API simplifies the creation of complex types, and it is relatively straight forward to use in your code.
Technically with Zod you are parsing a schema and not using it to validate. When you feed it data that isn't valid, the parser throws an error (you can also parse without throwing the error)
Tools like tRPC leverage Zod to give you relatively easy to use "full stack" types from your API through your client applications that are consuming the data.
Like Zod, Yup supports static type inference which makes it useful in a similar way to Zod.
Unfortunately Yup creates typings that aren't aligned with TypeScript, and this is means that it is less useful in the context of TypeScript.
Ready to pick up the pace?
Enter your email and receive regular updates on our latest articles and courses
We're here to help.
Sign up for our FREE email course
- ⭐️ Portfolio Building: Learn how to build a badass developer portfolio so you can land that next job
Joi doesn't support static type inference at all, so that makes the decision to check it off the list an easy one.
This is a great library, but it is 100% geared towards a functional programming (FP) style that is likely incompatible with how the majority of developers approach building applications with TypeScript.
If you already code in an FP style, this might be the choice for you, but it's verbose and a bit tedious if that's not how your app is already built and requires the
fp-ts library to use.
Conclusion: Zod is awesome
We are using Zod, and love it. It's modern, aligned with TypeScript and dang useful.
Matt Pocock's interactive video tutorial covering the basics of Zod is a great resource if you'd like to learn more about Zod!