npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

zod-to-defaults

v1.1.1

Published

Extract default values from Zod schemas for form initialization and testing

Readme

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