Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

zod

БесплатноБез исполняемых скриптовНе проверен

Zod schema validation patterns and type inference. Auto-loads when validating schemas, parsing data, validating forms, checking types at runtime, or using…

jpoutrinот jpoutrin★ 16 звёзд на GitHub16 установок в других каталогах

Об этом скилле

Zod Schema Validation

TypeScript-first schema declaration and validation library with static type inference.

Why Zod

  • Zero dependencies, 2kb gzipped
  • Works in Node.js and browsers
  • Immutable API - methods return new instances
  • Static type inference - no redundant type declarations
  • JSON Schema conversion built-in

Requirements

  • TypeScript v5.5+
  • Enable strict mode in tsconfig.json

Core Concepts

Schema Definition

Always define schemas before validation:

import { z } from "zod";

// Object schema
const UserSchema = z.object({
  id: z.string().uuid(),
  email: z.string().email(),
  age: z.number().int().positive(),
  role: z.enum(["admin", "user", "guest"]),
});

// Infer TypeScript type from schema
type User = z.infer<typeof UserSchema>;

Parsing Methods

.parse() - Throws ZodError on failure:

try {
  const user = UserSchema.parse(data);
  // user is typed as User
} catch (e) {
  if (e instanceof z.ZodError) {
    console.error(e.issues);
  }
}

.safeParse() - Returns discriminated union (preferred):

const result = UserSchema.safeParse(data);

if (result.success) {
  console.log(result.data); // typed User
} else {
  console.error(result.error.issues);
}

Async variants - Required for async refinements/transforms:

await UserSchema.parseAsync(data);
await UserSchema.safeParseAsync(data);

Primitive Types

// Basic primitives
z.string()
z.number()
z.bigint()
z.boolean()
z.date()
z.symbol()
z.undefined()
z.null()
z.void()
z.any()
z.unknown()
z.never()

// Coercion - converts input to target type
z.coerce.string()   // String(input)
z.coerce.number()   // Number(input)
z.coerce.boolean()  // Boolean(input)
z.coerce.bigint()   // BigInt(input)
z.coerce.date()     // new Date(input)

String Validations

z.string()
  .min(1)              // Minimum length
  .max(255)            // Maximum length
  .length(10)          // Exact length
  .email()             // Email format
  .url()               // URL format
  .uuid()              // UUID format
  .cuid()              // CUID format
  .regex(/pattern/)    // Custom regex
  .startsWith("prefix")
  .endsWith("suffix")
  .includes("substring")
  .trim()              // Transform: trim whitespace
  .toLowerCase()       // Transform: lowercase
  .toUpperCase()       // Transform: uppercase

Number Validations

z.number()
  .int()               // Integer only
  .positive()          // > 0
  .nonnegative()       // >= 0
  .negative()          // < 0
  .nonpositive()       // <= 0
  .gt(5)               // > 5
  .gte(5)              // >= 5 (alias: .min())
  .lt(10)              // < 10
  .lte(10)             // <= 10 (alias: .max())
  .multipleOf(5)       // Divisible by 5
  .finite()            // Excludes Infinity
  .safe()              // Safe integer range

Object Schemas

const PersonSchema = z.object({
  name: z.string(),
  age: z.number(),
});

// Make all properties optional
PersonSchema.partial();

// Make specific properties optional
PersonSchema.partial({ age: true });

// Make all properties required
PersonSchema.required();

// Pick specific properties
PersonSchema.pick({ name: true });

// Omit specific properties
PersonSchema.omit({ age: true });

// Extend with new properties
PersonSchema.extend({
  email: z.string().email(),
});

// Strict mode - reject unknown keys
PersonSchema.strict();

// Passthrough - preserve unknown keys
PersonSchema.passthrough();

// Strip unknown keys (default behavior)
PersonSchema.strip();

Arrays and Tuples

// Array of strings
z.array(z.string())
  .min(1)              // At least 1 element
  .max(10)             // At most 10 elements
  .length(5)           // Exactly 5 elements
  .nonempty();         // At least 1 element (typed)

// Alternative syntax
z.string().array();

// Tuple with fixed positions
z.tuple([
  z.string(),          // First element: string
  z.number(),          // Second element: number
]);

// Tuple with rest elements
z.tuple([z.string(), z.number()]).rest(z.boolean());

Unions and Enums

// Union types
z.union([z.string(), z.number()]);
// Shorthand
z.string().or(z.number());

// Discriminated unions (better error messages)
z.discriminatedUnion("type", [
  z.object({ type: z.literal("email"), email: z.string() }),
  z.object({ type: z.literal("phone"), phone: z.string() }),
]);

// Enum from array
z.enum(["admin", "user", "guest"]);

// Native enum
enum Role { Admin, User }
z.nativeEnum(Role);

Optional and Nullable

// Optional - allows undefined
z.string().optional();  // string | undefined

// Nullable - allows null
z.string().nullable();  // string | null

// Both
z.string().nullish();   // string | null | undefined

// Default values
z.string().default("anonymous");
z.string().optional().default("anonymous");

// Catch - use def
Полный SKILL.md на GitHub

Установить zod в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл zod?

Zod schema validation patterns and type inference. Auto-loads when validating schemas, parsing data, validating forms, checking types at runtime, or using z.object/z.string/z.infer in TypeScript.

Как установить скилл zod?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл zod запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить zod с