Zod is a TypeScript-first schema declaration and validation library used to define the shape of data in TypeScript. It allows you to create schemas for your data structures, validate incoming data against those schemas, and ensure type safety within your TypeScript applications.
Here's a simple example demonstrating how Zod can be used:
Typescript code
import * as z from 'zod';
// Define a schema for a user object
const userSchema = z.object({
id: z.string(),
username: z.string(),
email: z.string().email(),
age: z.number().int().positive(),
isAdmin: z.boolean(),
});
// Data to be validated against the schema
const userData = {
id: '123',
username: 'johndoe',
email: 'john@example.com',
age: 30,
isAdmin: true,
};
// Validate the data against the schema
try {
const validatedUser = userSchema.parse(userData);
console.log('Validated user:', validatedUser);
} catch (error) {
console.error('Validation error:', error);
}
```
In the above example:
1. We import `z` from 'zod', which provides access to Zod's functionality.
2. We define a schema for a user object using `z.object()`. Each property in the object has a specific type and validation constraint defined by Zod methods like `z.string()`, `z.number()`, `z.boolean()`, etc.
3. `userData` represents an object we want to validate against the schema.
4. We use `userSchema.parse()` to validate `userData` against the defined schema. If the data matches the schema, it returns the validated user object; otherwise, it throws a validation error.
Zod helps ensure that the incoming data adheres to the defined schema, providing type safety and validation within TypeScript applications. This prevents runtime errors caused by unexpected data shapes or types.