Skip to content

Extract default values from Zod schemas for form initialization and testing

License

Notifications You must be signed in to change notification settings

bokeeeey/zod-to-defaults

Repository files navigation

zod-to-defaults

Extract default and empty values from Zod schemas for seamless form initialization and testing

npm version npm downloads License: MIT

Why zod-to-defaults?

Zod는 강력한 타입 안전 스키마 검증 라이브러리이지만, 스키마로부터 초기값을 추출하는 기능은 제공하지 않습니다. 폼을 초기화하거나 테스트 데이터를 생성할 때, 스키마와 별도로 초기값을 관리하면 동기화 문제가 발생할 수 있습니다.

zod-to-defaults는 이 문제를 해결합니다:

  • 단일 진실 공급원: 스키마가 곧 초기값의 유일한 소스
  • 타입 안전성: Zod의 타입 추론을 그대로 활용
  • 유지보수성: 스키마 변경 시 초기값도 자동으로 동기화
  • 범용성: React Hook Form, TanStack Form 등 모든 폼 라이브러리와 호환

Installation

npm install zod-to-defaults
# or
yarn add zod-to-defaults
# or
pnpm add zod-to-defaults

Requirements:

  • Zod v3.0.0 이상 또는 v4.0.0 이상

Quick Start

import { z } from 'zod';
import { getSchemaDefaults } from 'zod-to-defaults';

const userSchema = z.object({
  name: z.string().default('Anonymous'),
  age: z.number(),
  email: z.string(),
  isActive: z.boolean(),
});

const defaults = getSchemaDefaults(userSchema);
// {
//   name: 'Anonymous',
//   age: 0,
//   email: '',
//   isActive: false
// }

API Reference

getSchemaDefaults<T>(schema: ZodType<T>): T

Zod 스키마로부터 기본값을 추출합니다. 각 타입별로 의미있는 기본값을 반환합니다:

Zod Type Default Value
z.string() ""
z.number() 0
z.boolean() false
z.date() new Date()
z.array() []
z.object() {} (각 필드의 기본값으로 채워짐)
z.enum() 첫 번째 옵션
z.literal() 리터럴 값
z.union() 첫 번째 옵션의 기본값
z.default(value) 지정된 value

getSchemaEmpties<T>(schema: ZodType<T>): T

Zod 스키마로부터 빈 값을 추출합니다. 폼 초기화 시 모든 필드를 비워야 할 때 유용합니다:

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

const empties = getSchemaEmpties(schema);
// { name: null, age: null }

Use Cases

1. React Hook Form Integration

import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { getSchemaDefaults } from 'zod-to-defaults';

const formSchema = z.object({
  username: z.string().min(3),
  email: z.string().email(),
  age: z.number().min(18).default(18),
});

function MyForm() {
  const form = useForm({
    resolver: zodResolver(formSchema),
    defaultValues: getSchemaDefaults(formSchema),
  });
  
  // ...
}

2. TanStack Form Integration

import { useForm } from '@tanstack/react-form';
import { getSchemaDefaults } from 'zod-to-defaults';

const userSchema = z.object({
  name: z.string(),
  email: z.string().email(),
});

function MyForm() {
  const form = useForm({
    defaultValues: getSchemaDefaults(userSchema),
    onSubmit: async ({ value }) => {
      // ...
    },
  });
  
  // ...
}

3. Complex Nested Schemas

const addressSchema = z.object({
  street: z.string(),
  city: z.string(),
  zipCode: z.string(),
});

const profileSchema = z.object({
  user: z.object({
    name: z.string().default('Guest'),
    age: z.number(),
  }),
  addresses: z.array(addressSchema),
  metadata: z.record(z.string()),
});

const defaults = getSchemaDefaults(profileSchema);
// {
//   user: { name: 'Guest', age: 0 },
//   addresses: [],
//   metadata: {}
// }

Advanced Features

Zod v3 & v4 Support

zod-to-defaults는 Zod v3와 v4를 모두 지원합니다. 내부적으로 버전별 차이를 자동으로 처리하여 동일한 API를 제공합니다.

// Zod v3와 v4 모두 동일하게 동작
const schema = z.enum(['active', 'inactive']);
const defaultValue = getSchemaDefaults(schema); // 'active'

Special Type Handling

// UUID 자동 생성
const schema = z.string().uuid();
getSchemaDefaults(schema); // crypto.randomUUID()

// IP 주소
z.string().ip(); // "0.0.0.0"
z.string().ipv6(); // "::"

// BigInt
z.bigint(); // BigInt(0)

// NaN
z.nan(); // NaN

// Template Literals (Zod v4)
z.templateLiteral`user_${z.string()}`; // "user_"

Comparison with Alternatives

Feature zod-to-defaults Manual defaults zod-mock
Type Safety
Zero Config
Zod v3 & v4 Support N/A ⚠️
Bundle Size ~2KB 0KB ~50KB
Randomization
Purpose Production Production Testing only

When to use zod-to-defaults:

  • 폼 초기값이 필요할 때
  • 스키마와 초기값을 동기화하고 싶을 때
  • 타입 안전한 기본값이 필요할 때

When to use alternatives:

  • 완전히 랜덤한 테스트 데이터가 필요할 때 → zod-mock
  • 번들 크기가 가장 중요할 때 → Manual defaults

Performance

  • 📦 Bundle size: ~2KB (minified + gzipped)
  • ⚡ Average execution time: < 1ms for typical schemas
  • 🎯 Zero dependencies (except Zod peer dependency)

TypeScript Support

완벽한 타입 추론을 제공합니다:

const schema = z.object({
  name: z.string(),
  age: z.number(),
  metadata: z.object({
    tags: z.array(z.string()),
  }),
});

const defaults = getSchemaDefaults(schema);
// Type: { name: string; age: number; metadata: { tags: string[] } }

defaults.name.toUpperCase(); // ✅ OK
defaults.age.toFixed(2); // ✅ OK
defaults.metadata.tags.push('new'); // ✅ OK

Contributing

기여는 언제나 환영합니다! 다음 절차를 따라주세요:

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Run tests (npm test)
  4. Commit your changes (git commit -m 'Add amazing feature')
  5. Push to the branch (git push origin feature/amazing-feature)
  6. Open a Pull Request

Development Setup

# Install dependencies
npm install

# Run tests
npm test

# Run tests with coverage
npm run test:coverage

# Build
npm run build

# Lint & Format
npm run check

License

MIT © bokeeeey

Links


Made with 🦖 by bokeeeey

About

Extract default values from Zod schemas for form initialization and testing

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 2

  •  
  •