zod library example in typescript
The "zod" library is a TypeScript-first schema validation library designed for use in JavaScript and TypeScript projects. It aims to provide a simple and expressive way to define and validate data schemas. Here are some key points about the "zod" library:
Features of Zod:
-
Type Safety: Zod is built with TypeScript in mind, so it leverages TypeScript's type system to ensure type safety throughout your application.
-
Schema Definition: It allows you to define schemas for data validation using a fluent and declarative API.
-
Data Validation: Zod provides powerful validation capabilities, including type checking, schema validation, and coercion of input data.
-
Asynchronous Validation: Supports asynchronous validation for cases where data validation involves asynchronous operations.
-
Custom Error Messages: You can customize error messages for validation failures, making it easier to provide clear feedback to users or developers.
-
Integration with React: Zod includes hooks and utilities for integrating with React applications, simplifying form validation and state management.
Example Usage:
Here’s a brief example of how you might use Zod to define a schema and validate data:
import { z } from 'zod';
// Define a schema
const userSchema = z.object({
id: z.string(),
username: z.string().min(3),
email: z.string().email(),
age: z.number().min(18),
});
// Validate data against the schema
const userData = {
id: '1',
username: 'john_doe',
email: '[email protected]',
age: 25,
};
try {
userSchema.parse(userData);
console.log('Validation passed');
} catch (error) {
console.error('Validation failed:', error.errors);
}