What is Zod? ๐ค
Zod is a TypeScript-first schema declaration and validation library. I am using โschemaโ to broadly refer to any data type, from a simple string to a complex nested object.
Zod is designed to be as developer-friendly as possible. The goal is to eliminate duplicative type declarations. With Zod, you declare a validator once and Zod will automatically infer the static TypeScript type. It is easy to compose simpler types into complex data structures.
Why Zod? ๐ค
For example, you can specify that the username property for a User should be a string.
However, you can not always be sure what you are going to get from a form input. TypeScript will present an error if it is not a string, but on its own, it does not know if a string length is too low or too high to be realistic for your use case.
There is a similar problem with third-party API responses.
You can reference documentation to get an idea for what a response includes, but TypeScript can not tell how to type it. And what happens if you get an error instead?
Zod allows you to work around uncertainty by checking types at the runtime level as well as the type level.
Great aspects:
๐ Zero dependencies
๐ Works in Node.js and all modern browsers
๐ Tiny: 8kb minified + zipped
๐ Immutable: methods (e.g. .optional()) return a new instance
๐ Concise, chainable interface
๐ Functional approach: parse, donโt validate
๐ Works with plain JavaScript too! You donโt need to use TypeScript.
I hope you found it useful. Thanks for reading. ๐
Let's get connected! You can find me on:
Hashnode: https://nhannguyen.hashnode.dev/
X (formerly Twitter): https://twitter.com/nhannguyendevjs/