Skip to content

Zod typescript first validation library: How to use with example

Zod typescript first validation library

In the world of TypeScript development, ensuring the integrity and consistency of data is crucial for building robust and reliable applications. That’s where Zod steps in – a powerful schema declaration and validation library designed specifically for TypeScript projects. In this article, we will explore the features and benefits of Zod and how it simplifies the process of defining, validating, and manipulating data structures in TypeScript.

What is Zod?

Zod is an open-source library that provides a concise and expressive way to define and validate data structures in TypeScript. It embraces the TypeScript type system and leverages its static type checking capabilities to catch errors early during development. With Zod, you can declare schemas for various data types such as objects, arrays, strings, numbers, booleans, and more.

TypeScript-First Approach

Unlike some other validation libraries, Zod takes a TypeScript-first approach. It integrates seamlessly with the TypeScript ecosystem and leverages type inference to provide accurate type annotations for your data structures. By utilizing TypeScript’s type system, Zod enables you to catch type errors at compile-time and ensures that your data conforms to the defined schemas.

Schema Declaration

With Zod, defining schemas is intuitive and concise. You can create schemas using a fluent API that offers a wide range of validation methods and combinators. Whether you need to specify required properties, set default values, validate data against regular expressions, or define complex nested structures, Zod provides a comprehensive set of tools to express your data constraints.

Validation

Once you have defined a schema, Zod allows you to easily validate your data against it. By invoking the .parse() method, Zod validates the input data and returns a strongly typed representation of the validated data. If the input fails validation, Zod throws a detailed error message indicating the specific validation failures. This approach ensures that only valid data passes through and helps you catch potential bugs early in the development cycle.

Transformation and Manipulation

Zod goes beyond validation by offering powerful transformation and manipulation capabilities. You can use methods like .transform() and .pick() to transform the validated data into a desired format or extract specific properties from the input. Zod’s combinators enable you to compose complex schemas by merging, intersecting, or excluding different schemas, allowing for fine-grained control over your data structures.

Integration and Ecosystem

Zod integrates seamlessly with popular frameworks and libraries within the TypeScript ecosystem. Whether you are building a Node.js application, a React frontend, or any other TypeScript-based project, Zod can be easily integrated to provide robust validation and type safety. It also provides integrations with libraries like Express and TypeORM, making it a versatile choice for various development scenarios.

Example that demonstrates how to use Zod for schema declaration and validation in TypeScript

import { z } from "zod";

// Define a schema for a user object
const userSchema = z.object({
  id: z.string().uuid(),
  name: z.string().min(3),
  email: z.string().email(),
  age: z.number().positive(),
  isAdmin: z.boolean().optional(),
});

// Valid data
const validData = {
  id: "3d4e55f1-5f02-4f88-aaec-984ded85869e",
  name: "John Doe",
  email: "johndoe@example.com",
  age: 25,
};

// Invalid data
const invalidData = {
  id: "invalid-uuid",
  name: "JD",
  email: "invalid-email",
  age: -5,
};

// Validate the data against the schema
try {
  const parsedData = userSchema.parse(validData);
  console.log("Valid data:", parsedData);
} catch (error) {
  console.error("Validation error:", error);
}

// Validation error will be thrown for invalidData
try {
  const parsedData = userSchema.parse(invalidData);
  console.log("Valid data:", parsedData);
} catch (error) {
  console.error("Validation error:", error);
}

In this example, we start by importing the necessary functions and types from the Zod library. We define a userSchema using the z.object() method, which represents a schema for a user object. The schema includes properties such as id, name, email, age, and an optional property isAdmin. Each property has specific validation rules applied using Zod’s fluent API.

We then demonstrate the validation process by attempting to parse the validData and invalidData objects against the defined userSchema. When the parse() method is called on a Zod schema, it either returns the parsed and validated data or throws an error if the data fails validation. In the example, we wrap the parse() calls in try-catch blocks to handle validation errors gracefully.

If the data passes validation, the parsed data is logged to the console. Otherwise, the validation error is caught and logged as an error message.

This example showcases the basic usage of Zod for schema declaration and validation. You can explore more of Zod’s features, such as transformations, combinations, and advanced validations, by referring to the official Zod documentation.

Conclusion

Zod is a TypeScript-first schema declaration and validation library that empowers developers to define, validate, and manipulate data structures with ease. Its integration with the TypeScript type system ensures early error detection, providing increased confidence in the correctness of your code. With its intuitive API, comprehensive validation features, and ecosystem integrations, Zod proves to be a valuable tool for building type-safe and reliable TypeScript applications. Whether you are working on a small project or a large-scale application, Zod can help you streamline your data validation workflow and reduce the likelihood of runtime errors.

Further Reading

Vite React: How to achieve faster and better build

Please share