今日已更新 80 条资讯 | 累计 20052 条内容
关于我们

Type-Safe Env Vars Without Zod

Odejobi Abiola Samuel 2026年06月25日 20:41 1 次阅读 来源:Dev.to

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 l

本文内容来源于互联网,版权归原作者所有
查看原文