Exploring Zod: A Comprehensive Guide
Tags: zod, typescript, webdev, javascript
Published: 2024-01-25 17:51:03

## Introduction
In the world of **TypeScript**, sometimes, the **Typescript validations** are not enough for us. In those situations, we want more control over the validations to make our code more robust. This is where **Zod** comes into the picture. 

## What is Zod?
**Zod** is a **TypeScript-first schema declaration and validation library**. It was created and developed by **Vercel**. It aims to make it easy for developers to define, validate and transform the data structures.

## Getting Started With Zod
First, create a **TypeScript project** and then install **Zod** with **npm** by using the following command:
```bash
npm install zod
```
If you are using **yarn**, use the following command:
```bash
yarn add zod
```
If you are using **pnpm**, use the following command:
```bash
pnpm add zod
```
Also, make sure that you are using `TypeScript 4.5+` and you enable `strict` mode in your `tsconfig.json` file.
```json
// tsconfig.json
{
  // ...
  "compilerOptions": {
    // ...
    "strict": true
  }
}
```
Then, create a typescript file called `index.ts` and import the `z` object from the `zod`. 

```javascript
import { z } from 'zod';
```
This `z` helps you to define your schemas. 
```javascript
import { z } from 'zod';

const ageSchema = z.number();

ageSchema.parse(12); // it will works fine
ageSchema.parse('hello'); // this will throws an error from zod
```
For the `ageSchema.parse('hello')` method call, you will get an error from `zod`. It will look like this:
```javascript
Error: [
{
"code": "invalid_type",
"expected": "number",
"received": "string",
"path": [],
"message": "Expected number, received string"
}
]
``` 
If you don't want **Zod** to throw an error, then use `safeParse()` instead of `parse()`
## Deep Dive into Zod
In **Zod**, you can define the schemas for your data. Then, these schemas will do all the validation work for you. In **Zod**, there are a lot of primitive types available:
```javascript
import { z } from 'zod';

// primitive types
z.number();
z.string();
z.bigint();
z.boolean();
z.date();
z.symbol();

// any types
z.any();
z.unknown();

// empty types
z.undefined();
z.null();
z.void();

// never type allows no value
z.never();
```
Now you may be thinking, I can also do this using TypeScript. What Zod can do more? You can also chain validator functions to enforce more strictness in your schemas:
```javascript
import { z } from 'zod';

const nameSchema = z.string().max(5);
const emailSchema = z.email();
const emojiSchema = z.string().emoji();
```
After learning this much you must be like:

![Wow Image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3donwpp2gk80w7wcuqn1.gif)
But I have more for you.
## Real World Zod Use Case:
Let's say you want to build a User Register page. Here, you can use Zod to make the validation more strict. Example:
```javascript
import { z } from 'zod';

const userSchema = z.object({
 firstName: z.string().nonempty(),
 lastName: z.string().optional(),
 email: z.string().email('Invalid email format').required('Email is required'),
 password: z.string().min(8, 'Password must be at least 8 characters').max(32).required()
});

// sample form data
const formData = {
 firstName: 'John',
 lastName: 'Doe',
 email: 'johndoe@gmail.com',
 password: 'john123'
};

// validate form data against userSchema
try {
 const parseData = userSchema.parse(formData);
 console.log('Validation Successful: ', formData);
 // if data is valid, then proceed with register
} catch(error) {
 if(error instanceof ZodError) {
  console.error('Validation failed. Errors:', error.errors);
 } else {
  console.error('Unexpected error during validation:', error.message);
 }
}

```

## Conclusion
**Zod** is a powerful and intuitive library that enhances the TypeScript development experience by providing a seamless way to make the code more robust. Head over to [zod.dev](https://zod.dev/) for the official documentation, tutorials, and examples