Zod
БесплатноБез исполняемых скриптовНе проверенExpert guidance for Zod schema validation including type inference, schema composition, parsing, refinements, transformations, error handling, and TypeScript…
Об этом скилле
Zod
Expert assistance with Zod - TypeScript-first schema validation.
Overview
Zod is a TypeScript-first schema declaration and validation library:
- Type Inference: Automatic TypeScript type inference
- Zero Dependencies: No runtime dependencies
- Composable: Build complex schemas from simple ones
- Developer Experience: Excellent autocomplete and error messages
Installation
npm install zod
Basic Usage
import { z } from 'zod';
// Define schema
const userSchema = z.object({
name: z.string(),
age: z.number(),
email: z.string().email(),
});
// Infer TypeScript type
type User = z.infer<typeof userSchema>;
// type User = { name: string; age: number; email: string }
// Parse data (throws on validation error)
const user = userSchema.parse({
name: 'John',
age: 30,
email: '[email protected]',
});
// Safe parse (returns result object)
const result = userSchema.safeParse({ name: 'John', age: '30' });
if (result.success) {
console.log(result.data);
} else {
console.error(result.error);
}
Primitive Types
// String
z.string();
z.string().min(5);
z.string().max(100);
z.string().length(10);
z.string().email();
z.string().url();
z.string().uuid();
z.string().regex(/^[a-z]+$/);
z.string().startsWith('https://');
z.string().endsWith('.com');
// Number
z.number();
z.number().int();
z.number().positive();
z.number().negative();
z.number().min(0);
z.number().max(100);
z.number().multipleOf(5);
// Boolean
z.boolean();
// Date
z.date();
z.date().min(new Date('2024-01-01'));
z.date().max(new Date('2025-01-01'));
// Literal
z.literal('admin');
z.literal(42);
z.literal(true);
Complex Types
// Object
const userSchema = z.object({
name: z.string(),
age: z.number(),
});
// Array
z.array(z.string());
z.array(z.number()).min(1).max(10);
// Tuple
z.tuple([z.string(), z.number(), z.boolean()]);
// Union (OR)
z.union([z.string(), z.number()]);
z.string().or(z.number()); // Same as above
// Discriminated Union
const shapeSchema = z.discriminatedUnion('kind', [
z.object({ kind: z.literal('circle'), radius: z.number() }),
z.object({ kind: z.literal('rectangle'), width: z.number(), height: z.number() }),
]);
// Intersection (AND)
const baseUser = z.object({ id: z.string() });
const namedUser = z.object({ name: z.string() });
const user = z.intersection(baseUser, namedUser);
// Or use extend
const user = baseUser.extend({ name: z.string() });
// Enum
z.enum(['admin', 'user', 'guest']);
z.nativeEnum(MyEnum);
// Record
z.record(z.string()); // { [key: string]: string }
z.record(z.string(), z.number()); // { [key: string]: number }
// Map
z.map(z.string(), z.number());
// Set
z.set(z.string());
Modifiers
// Optional
z.string().optional(); // string | undefined
z.object({ name: z.string().optional() });
// Nullable
z.string().nullable(); // string | null
// Nullish (optional + nullable)
z.string().nullish(); // string | null | undefined
// Default
z.string().default('default value');
z.number().default(0);
// Catch (provide fallback on parse error)
z.string().catch('fallback');
Refinements
// Custom validation
const passwordSchema = z.string().refine(
(val) => val.length >= 8,
{ message: 'Password must be at least 8 characters' }
);
// Multiple refinements
const schema = z.string()
.min(8)
.refine((val) => /[A-Z]/.test(val), {
message: 'Must contain uppercase letter',
})
.refine((val) => /[0-9]/.test(val), {
message: 'Must contain number',
});
// Superrefine (access ctx for multiple errors)
const schema = z.string().superRefine((val, ctx) => {
if (val.length < 8) {
ctx.addIssue({
code: z.ZodIssueCode.too_small,
minimum: 8,
type: 'string',
inclusive: true,
message: 'Too short',
});
}
if (!/[A-Z]/.test(val)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Must contain uppercase',
});
}
});
Transformations
// Transform value
const schema = z.string().transform((val) => val.toLowerCase());
// Chain transforms
const schema = z.string()
.transform((val) => val.trim())
.transform((val) => val.toLowerCase());
// Transform to different type
const numberSchema = z.string().transform((val) => parseInt(val, 10));
// Preprocess before validation
const schema = z.preprocess(
(val) => (typeof val === 'string' ? val.trim() : val),
z.string().min(1)
);
Object Methods
const userSchema = z.object({
id: z.string(),
name: z.string(),
email: z.string(),
age: z.number(),
});
// Pick fields
const nameOnly = userSchema.pick({ name: true });
// Omit fields
const withoutId = userSchema.omit({ id: true });
// Partial (all fields optional)
const partialUser = userSchema.partial();
// Deep Partial
const deepPartial = userSchema.deepPartial();
// Required (make all fields required)
const required = partialUser.required();
Установить Zod в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл Zod?
Expert guidance for Zod schema validation including type inference, schema composition, parsing, refinements, transformations, error handling, and TypeScript integration. Use this when building type-safe validation, form validation, or API input validation.
Как установить скилл Zod?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл Zod запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic