DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

5

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:

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay