Type safety - The power of Zod
Tags: webdev, typescript, tutorial, codequality
Published: 2023-03-19 03:58:59

In our applications we always have the need to validate the information that we receive from either a user input or from an external API. TypeScript has given us tools to have type safety but it is _only_ on development it will not work on runtime.

Since we need to check our data on runtime, we have the need to either write code to validate it or we can use a library to help us with it. That is where the `zod` comes into play, it is a library that helps us with type safety during development and as runtime checker.

## Installing Zod

Lets continue with the TypeScript project we've been building in my previous posts. To install zod, in the terminal we need to write:

```bash
npm install zod
```

## Basic usage

To work with `zod` we need to write schemas which we will be using to validate the input to our application, and we have two main ways to validate that the inputs meet our expectations

```TypeScript
import { z } from "zod";

const mySchema = z.string();

// parsing data

const data = mySchema.parse("hello"); // data will be of type string with the value "hello"
const error = mySchema.parse(36);     // this will throw an error of type ZodError

// safe parsing

const data = mySchema.safeParse("hello");
// data will be an object with the following properties
// data.success will be equal to true
// data.data will have the value "hello"

const error = mySchema.safeParse(42);
// error will be an object with the following properties
// data.success will be equal to false
// data.error will be an object of type ZodError
```

What we are doing on the example above is to define a schema to validate with the data we receive, and we are expecting a string and after we parse the data we get back if we either have a string or we get an error.

## Creating schemas

In the basic usage section we learned we can create schemas to validate our data with. The schemas can be as simple as the above example or with more complexity, we will look at some of the ways we can create schemas, for more information you can go through the [zod](https://zod.dev) documentation.

### Primitive schemas

Primitive schemas is the most basic form of creating a schema, we define them like this

```TypeScript
import { z } from "zod";

const stringSchema = z.string();
const numberSchema = z.number();
const bigIntSchema = z.bigint();
const booleanSchema = z.boolean();
const dateSchema = z.date();
```

In each of the schemas we can add more constraints to have more control about the data we receive, for example we can add the `.optional()` to each, in that way we specify that the specific value can be undefined

```TypeScript
import { z } from "zod";

const stringSchema = z.string().optional();

const undefinedValue = undefined;

stringSchema.parse(undefinedValue)
// This validation will pass since we are allowing our schema to be undefined
```

### Object schemas

I will show you how to define an object schema, each of the properties can be either a primitive, object or other kind of schema.

```TypeScript
import { z } from "zod";

const userSchema = z.object({
    id: z.string().uuid(),
    email: z.string().email(),
    name: z.string(),
    age: z.number().int().positive(),
    address: z.object({
        street: z.string(),
        city: z.string()
    }).optional()
});
```

In this schema we have many properties, in some of those we added more constraints wich in general are self explanatory.

### Other kind of schemas

With `zod` we can define schemas for any of the types we have in TypeScript, meaning we can have

- arrays
- maps
- tuples
- sets
- unions
- promises

And also we have more advaced schemas definitions.

## Practical example

Lets install zod

![install zod](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vvbwcsp6gu5bmublz867.png)

This is the code we currently have

![non zod code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ncg6x2k3k5bxl5c8guw.png)

Lets add a user schema

![user schema](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x3ehovetn60esa0ns5ht.png)

Data validation

![data validation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/50aafhiqueuk6kfjwlig.png)

With the above example we make sure that the data we receive complies with the user schema we expect both during development and most important on runtime

## Conclusion

In conclusion, zod is a powerful and easy to use validator that will help us ensure the data is accurate and in the right format. Give it a try and see how it will help you to improve the quality of your code and reduce bugs due to invalid data