DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

Zod - TypeScript-first schema declaration and validation library #1

Image description

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:

Top comments (0)