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 從公開儲存庫中收錄這些內容。

檢舉或申請下架