banner image 1 banner image 2

ZOD — TypeScript-first schema validation with static type inference

November 24, 2022
5 mins
command
blog-img 1
Saiganesh Sampathirao
Author

This article gives you a basic understanding of working with modern validator ZOD in JS frameworks.

By Saiganesh Sampathirao — “Commitment Matters!”

ZOD in JS frameworks
Zod

Introduction to ZOD

Zod is a TypeScript-first schema declaration and validation library. I’m using the term “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’s easy to compose simpler types into complex data structures.

INSTALLATION

Node/NPM

To install Zod v3:

npm install zod       # npm
yarn add zod # yarn
pnpm add zod # pnpm

Requirements

  • TypeScript 4.1+!
  • You must enable strict the mode in your tsconfig.json. This is a best practice for all TypeScript projects.
// tsconfig.json 
{
// …
"compilerOptions": {
// …
"strict": true }
}

Deno

Unlike Node, Deno doesn’t use a package manager like NPM and instead relies on direct URL imports. You may access Zod at deno.land/x.

This is how the most recent version can be imported:

import { z } from "https://deno.land/x/zod/mod.ts";

You can also specify a particular version:

import { z } from "https://deno.land/x/zod@v3.16.1/mod.ts";

Basic usage

Creating a simple string schema

import { z } from "zod";
// creating a schema for strings
const mySchema = z.string();
// parsing
mySchema.parse("tuna"); // => "tuna"
mySchema.parse(12); // => throws ZodError
// "safe" parsing (doesn't throw error if validation fails)
mySchema.safeParse("tuna"); // => { success: true; data: "tuna" }
mySchema.safeParse(12); // => { success: false; error: ZodError }

Creating an object schema

import { z } from "zod";
const User = z.object({
username: z.string(),
});
User.parse({ username: "Ludwig" });
// extract the inferred type
type User = z.infer<typeof User>;
// { username: string }

Primitives

import { z } from "zod";
// primitive values
z.string();
z.number();
z.bigint();
z.boolean();
z.date();
z.symbol();
// empty types
z.undefined();
z.null();
z.void(); // accepts undefined
// catch-all types
// allows any value
z.any();
z.unknown();
// never type
// allows no values
z.never();

WHY ZOD?

We live in a competitive environment.

All we need is a tool that makes the process easier while prioritizing accuracy.

The following characteristics of ZOD make it a good validator:

* Developer Friendly and TypeSafe :

ZOD validator is type-safe because intrinsic functions do the validation. The ZOD validator avoids common human errors that are expected to occur in most of the validators. The errors can be noticed at the developer level.

Here,

In figure: 1 below, As ZOD has intrinsic functionalities, it enables developers like us to be aware of any errors we are experiencing unknowledgeably.

ZOD intrinsic functionalities
fig:1

* Minimal code :

ZOD is used to reduce the amount of code because ZOD is a type script first schema. Internal functions perform the validation.

Take the below scenario as an illustration:-

Valid: Any array of 2 or 3 integers, [1, 2], [1, 2, 3], etc.

Invalid: Any array with fewer than 2 or more than 3 numbers is [], [1, “foo,”], [1, 2, 3, 4].

One straightforward single line can serve as the validation for this scenario using ZOD.

z.array(z.int()).max(3).min(2)

* Easy to understand and flexible :

ZOD is simple for developers to comprehend and demonstrates its adaptability by developing inner functions for nested validations.

For a newbie, it is also incredibly adaptable and simple to understand.

zodValidation
zodValidation

* Custom Validations :

In Zod, we can give custom validations. Unlike most of the other validators using regex, In Zod, we can provide custom validations with simple javascript functions using the keyword “REFINE”.

For example, here below

Custom validation for the attribute FDD is done using refine where the inner function is in javascript.

zodValidation
zodValidation

* Custom error messages :

ZOD, In this Inner filter, can also receive personalized, meaningful error messages.

For example, in the below figure, we can see the different types of meaningful error messages that were given for each inner filter like for

Length — ‘ must be of 2 values only i.e from date to To date in YYYY-MM-DD’.

Refine(Custom Validation) — ‘The FROM Date should be less than or equal to the TO date and should be valid. ‘

Zod in JS Frameworks
Zod in JS Frameworks

This feature also gives the ZOD a lot more weight.

Some Other Great Aspects of ZOD

  • Zero dependencies
  • Works in Node.js and all modern browsers
  • Tiny: 8kb minified + zipped
  • Immutable: methods (i.e. .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.

CONCLUSION

Zod is designed to be as developer-friendly as possible.

The intention is to get rid of redundant type declarations.

With Zod, you only need to declare a validator once, and Zod will figure out the static TypeScript type on its own. Simpler types can be combined into more complex ones quite easily.


Meet the team!

Author
Saiganesh Sampathirao

Editor
Mridula Saravanan


We at CaratLane are solving some of the most intriguing challenges to make our mark in the relatively uncharted omnichannel jewellery industry. If you are interested in tackling such obstacles, feel free to drop your updated resume/CV to careers@caratlane.com.
blog-img 2

Discussions

blog-img 3
5 mins
May 17, 2023
Sharing Data Between Controllers: Best Practices S...

This article will help you to understand the diffe

By Naveen C

blog-img 3
5 mins
March 21, 2023
Understanding Auto Layout and Constraints in Swift...

This article gives you an easy way of understandin

By Ramasamy P