How to Use Zod for Advanced Data Validation in TypeScript
Master Type Safety with Zod: Streamline Data Validation and Schema Management in TypeScript
Zod is a TypeScript library for schema-based validation and data type enforcement. It simplifies type management, ensuring data safety at both compile and runtime.
Key Benefits and Usage
Type Generation: Automatically creates TypeScript types from Zod schemas, eliminating the need for duplicate code.
Advanced Validations: Supports async validation, custom validators, and condition-based checks.
Modular Schemas: Allows composition and extension of schemas for complex structures.
Example Usages
Basic Schema Validation:
const userSchema = z.object({
name: z.string(),
age: z.number(),
email: z.string().email(),
});
const user = userSchema.parse({ name: "Rob", age: 42, email: "alice@example.com" });
API Data Validation: Ensures data from external APIs conforms to the expected structure.
const apiResponseSchema = z.object({
data: z.array(z.object({
id: z.number(),
title: z.string(),
})),
});
Configuration Validation: Validates environment variables for consistent configuration.
const configSchema = z.object({
PORT: z.string().regex(/^\d+$/).transform(Number),
DATABASE_URL: z.string().url(),
});
const config = configSchema.parse(process.env);
Complex Forms: Useful for validating forms in UI frameworks like React.
const formDataSchema = z.object({
fields: z.array(z.object({
label: z.string(),
value: z.union([z.string(), z.number()]),
})),
});
Zod’s flexibility in handling diverse data structures makes it ideal for applications requiring strict data integrity and error prevention across various environments. What unique use cases have you found for Zod?
```ts
const configSchema = z.object({
PORT: z.coerce.number(),
DATABASE_URL: z.string().url(),
});
```
This could be an alternative if you just want to have a number for `PORT`