DEV Community

Andres Court
Andres Court

Posted on

Type safety - The power of Zod

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:

npm install zod
Enter fullscreen mode Exit fullscreen mode

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

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
Enter fullscreen mode Exit fullscreen mode

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 documentation.

Primitive schemas

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

import { z } from "zod";

const stringSchema = z.string();
const numberSchema = z.number();
const bigIntSchema = z.bigint();
const booleanSchema = z.boolean();
const dateSchema = z.date();
Enter fullscreen mode Exit fullscreen mode

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

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
Enter fullscreen mode Exit fullscreen mode

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.

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()
});
Enter fullscreen mode Exit fullscreen mode

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

This is the code we currently have

non zod code

Lets add a user schema

user schema

Data validation

data validation

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

Top comments (0)