惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Vercel News
Vercel News
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
雷峰网
雷峰网
有赞技术团队
有赞技术团队
罗磊的独立博客
博客园 - 叶小钗
Jina AI
Jina AI
博客园 - 司徒正美
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
T
Tailwind CSS Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
人人都是产品经理
人人都是产品经理
Apple Machine Learning Research
Apple Machine Learning Research
阮一峰的网络日志
阮一峰的网络日志
Microsoft Security Blog
Microsoft Security Blog
大猫的无限游戏
大猫的无限游戏
量子位
MyScale Blog
MyScale Blog
V
Visual Studio Blog
博客园 - 聂微东
The Cloudflare Blog
Engineering at Meta
Engineering at Meta
小众软件
小众软件
宝玉的分享
宝玉的分享

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Type-Safe Env Vars Without Zod
Odejobi Abiola Samuel · 2026-06-25 · via DEV Community
Cover image for Type-Safe Env Vars Without Zod

Odejobi Abiola Samuel

Most TypeScript projects treat environment variables like second-class citizens. They're string | undefined everywhere, asserted with ! and parsed with parseInt(). TypeScript can't help because process.env is typed as Record<string, string | undefined>.

Schema-based validation fixes this. But most solutions bring zod, which adds 50 KB to your bundle. CtroEnv does it with zero dependencies and 6.5 KB gzipped.

How Inference Works

The type system reads each validator's configuration at compile time:

type InferredValue<V> =
  V extends Validator<infer T>
    ? V["metadata"] extends { hasDefault: true }
      ? T                    // .default() → non-nullable
      : V["metadata"] extends { optional: true }
        ? T | undefined      // .optional() → nullable
        : T                  // required → guaranteed present
    : never

This means the schema defines the type:

const env = defineEnv({
  PORT: number().port().default(3000),
  // ^? number — default makes it always present

  DB_URL: string().url(),
  // ^? string — required

  DEBUG: boolean().optional(),
  // ^? boolean | undefined — optional

  NODE_ENV: pick(["dev", "prod", "staging"] as const),
  // ^? "dev" | "prod" | "staging" — exact union
})

No interface Env { ... }. No z.infer<typeof Schema>. Add a new validator, and the type updates automatically.

Default vs Optional vs Required

The three states and their types:

Declaration Type Runtime behavior
string() string Required — throws if missing
string().optional() `string \ undefined`
string().default("x") string Falls back to "x"
string().optional().default("x") string Default overrides optional

TypeScript reflects this exactly. Optional gives you | undefined. Default removes it.

The as const Requirement

pick() needs as const to preserve literal types:

pick(["dev", "prod"])           // type: string — widened
pick(["dev", "prod"] as const)  // type: "dev" | "prod" — exact union

Without as const, TypeScript widens the array to string[] and you lose the union.

Exhaustive Checking

With exact literal types, you get exhaustive checking:

switch (env.NODE_ENV) {
  case "dev": break
  case "prod": break
  case "staging": break
  // TypeScript error if you forget a case — and you can't match "production"
  // because it's not in the union
}

The Chain Order Gotcha

Type-specific methods (.url(), .email(), .min()) must come before chainable methods (.secret(), .optional(), .describe()):

string().url().secret()     // ✅ correct
string().secret().url()     // ❌ — .url() doesn't exist after .secret()

Reason: .secret() returns a generic Validator & ChainableMethods wrapper. The type-specific methods like .url() only exist on StringValidator. Once you call a chainable method, those are gone.

Quick reference:

// ✅ Correct
string().min(1).max(255).url().secret()
number().int().positive().default(42)
pick(["a", "b"] as const).optional()
boolean().default(false)

// ❌ Wrong
string().secret().url()    // .url() lost
number().optional().int()  // .int() lost

pick(), boolean(), semver(), ip(), uuid() have no type-specific refinements, so chain order doesn't matter for them.

Composing Schemas

defineSchema() + extendSchema() preserve full types through composition:

import { defineSchema, extendSchema } from "@ctroenv/core"

const base = defineSchema({
  NODE_ENV: pick(["dev", "prod"] as const).default("dev"),
})

const schema = extendSchema(base, {
  PORT: number().port().default(3000),
})

const env = defineEnv(schema)
// env.NODE_ENV: "dev" | "prod"
// env.PORT: number

The composed type merges both schemas. Extension keys override base keys — with a dev-mode warning on conflicts.

Compared to Zod

// zod — 50 KB dependency
import { z } from "zod"
const Schema = z.object({
  PORT: z.coerce.number().min(1).max(65535).default(3000),
  DB_URL: z.string().url(),
})
type Env = z.infer<typeof Schema>

// CtroEnv — 6.5 KB, zero deps
import { defineEnv, string, number } from "@ctroenv/core"
const env = defineEnv({
  PORT: number().port().default(3000),
  DB_URL: string().url(),
})
// ^? { PORT: number; DB_URL: string } — inferred automatically

Same validation power. No manual type extraction. No extra dependency.

npm install @ctroenv/core

Links: GitHub · Docs · npm

Previous: Why Your .env File Is Lying to You
Next: Framework-Specific Env Patterns