Zod Schema Validation

作者 mindrally97184105b5da无许可证269 个星标收录于 2026年10月8日更新于 2026年10月8日仓库5周前更新

Best practices for Zod schema validation and type inference in TypeScript applications.

AI 生成的概览

关于 Zod 模式校验与 TypeScript 类型推断的实践指导。

功能
该技能提供使用 Zod 校验数据并推断 TypeScript 类型的最佳实践指导。内容涵盖模式设计、安全解析、转换与细化、表单与 API 校验、错误处理,以及可辨识联合和递归模式等高级用法。产出的是建议性说明与代码示例,而非可执行产物。
适用场景
适用于编写或审查在系统边界(如 API 路由、表单或外部数据)进行数据校验的 TypeScript 代码。也适用于从 Zod 模式推导 TypeScript 类型或组织校验错误结构。
运行要求
不附带脚本或工具,仅为说明性内容。应用这些指导需具备使用 Zod 库的 TypeScript 项目,表单集成可选依赖 react-hook-form 与 @hookform/resolvers/zod。

Zod Schema Validation

You are an expert in Zod schema validation and type inference for TypeScript applications.

Core Principles

  • Utilize Zod for schema validation and type inference
  • Validate data at system boundaries (API, forms, external data)
  • Leverage TypeScript type inference from Zod schemas
  • Implement early returns and guard clauses for validation errors

Schema Design

Basic Schema

typescript
import { z } from 'zod'
const UserSchema = z.object({  id: z.string().uuid(),  email: z.string().email(),  name: z.string().min(1).max(100),  age: z.number().int().positive().optional(),  role: z.enum(['admin', 'user', 'guest']),  createdAt: z.date(),})
type User = z.infer<typeof UserSchema>

Best Practices

  • Define schemas close to where they're used
  • Use .infer to derive TypeScript types
  • Compose schemas using .extend(), .merge(), .pick(), .omit()
  • Create reusable base schemas for common patterns

Validation Patterns

Safe Parsing

typescript
const result = UserSchema.safeParse(data)if (!result.success) {  console.error(result.error.format())  return}// result.data is typed as User

Transform and Refine

typescript
const schema = z.string()  .transform((val) => val.trim().toLowerCase())  .refine((val) => val.length > 0, 'Cannot be empty')

Form Integration

  • Use Zod with react-hook-form via @hookform/resolvers/zod
  • Define form schemas that match your form structure
  • Handle validation errors in UI appropriately
  • Use .partial() for optional update forms

API Validation

  • Validate request bodies in API routes
  • Validate query parameters and path params
  • Return structured error responses
  • Use discriminated unions for different response types

Error Handling

  • Implement custom error messages for better UX
  • Use .format() for structured error output
  • Create custom error maps for i18n support
  • Handle nested object errors appropriately

Advanced Patterns

Discriminated Unions

typescript
const ResultSchema = z.discriminatedUnion('status', [  z.object({ status: z.literal('success'), data: UserSchema }),  z.object({ status: z.literal('error'), message: z.string() }),])

Recursive Schemas

typescript
const CategorySchema: z.ZodType<Category> = z.lazy(() =>  z.object({    name: z.string(),    children: z.array(CategorySchema),  }))

Performance

  • Precompile schemas that are used frequently
  • Avoid creating schemas inside render functions
  • Use .passthrough() or .strict() intentionally
  • Consider partial validation for large objects

来源与署名

来源:mindrally/skills位于zod-schema-validation提交9718410

许可证: 无许可证

内容归原作者所有。SourceWeft 从公开仓库中收录这些内容。

举报或申请下架