Type-Safe Env Vars Without Zod
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