In the world of TypeScript, maintaining data integrity and ensuring type safety are paramount. Enter Zod, a powerful runtime checking library that provides robust validation and manipulation of data structures. With Zod, developers can enforce strict data schemas and perform runtime checks, safeguarding applications against invalid data. In this blog post, we will explore the wonders of runtime checking with Zod, diving into its key features and practical examples to showcase how it elevates TypeScript development.

What is Zod ?

Zod is a TypeScript-first runtime validation library that enables developers to define strict schemas for their data and validate incoming data against those schemas at runtime. Unlike traditional compile-time type checking, Zod extends the type system to runtime, offering a seamless way to enforce data integrity and prevent errors due to unexpected data.

Installing Zod:

To get started with Zod, install the package from npm:

npm install zod

Defining and Validating Schemas with Zod

Let's begin by defining a simple schema using Zod to validate user objects:

import { z } from "zod";

const userSchema = z.object({
  name: z.string(),
  age: z.number().min(18),
  email: z.string().email(),
});

const validUserData = {
  name: "John Doe",
  age: 25,
  email: "[email protected]",
};

const invalidUserData = {
  name: "Jane Doe",
  age: 16,
  email: "invalid_email",
};

try {
  userSchema.parse(validUserData);
  console.log("Valid user data!");
} catch (error) {
  console.error("Invalid user data:", error.message);
}

try {
  userSchema.parse(invalidUserData);
  console.log("Valid user data!");
} catch (error) {
  console.error("Invalid user data:", error.message);
}

In this example, we define a schema using z.object, which represents an object with three properties: name, age, and email. We specify the expected types and any additional validation rules using Zod's methods like z.string(), z.number(), and z.email(). we use userSchema.parse() to validate the validUserData and invalidUserData. Zod will throw an error with a helpful error message for the invalid data, ensuring that only valid data passes through.


Verify Unknown APIs with Schema Object in Zod

When dealing with APIs that return dynamic or unknown data structures, it becomes crucial to ensure that the received data adheres to specific rules or contracts. Traditional TypeScript type checking may not be sufficient in such scenarios, as the data shapes can vary. This is where Zod comes to the rescue.

To verify unknown APIs, we can define a flexible object schema with Zod. For instance, let's assume we expect an API to return an object with a name and an optional age field.

import { z } from "zod";

const unknownAPISchema = z.object({
  name: z.string(),
  age: z.number().optional(),
});