ZOD — TypeScript-first schema validation with static type inference
By Saiganesh Sampathirao — “Commitment Matters!”
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.
To install Zod v3:
npm install zod # npm
yarn add zod # yarn
pnpm add zod # pnpm
strict
the mode in your tsconfig.json
. This is a best practice for all TypeScript projects.// tsconfig.json
{
// …
"compilerOptions": {
// …
"strict": true }
}
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";
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 }
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();
We live in a competitive environment.
All we need is a tool that makes the process easier while prioritizing accuracy.
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 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)
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.
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.
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. ‘
This feature also gives the ZOD a lot more weight.
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.
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.
Leave a Reply