Typing Environment Variables
Give process.env a precise, validated type.
Typing Environment Variables is a free TypeScript Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the TypeScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
The Problem with process.env
In Node, process.env is typed as Record<string, string | undefined>. Every variable might be missing, and everything is a string, so raw access is unsafe and untyped.
Declaring a Typed Env Interface
Start by describing the configuration your app actually needs as a precise interface, with correct types and required versus optional fields.
interface Env {
PORT: number;
NODE_ENV: "development" | "production";
DATABASE_URL: string;
DEBUG?: boolean; // optional
}Reading Raw Values
All values arrive as strings or undefined. You must read them defensively, because the keys may simply not be present.
const rawPort = process.env.PORT; // string | undefined
const rawEnv = process.env.NODE_ENV; // string | undefinedRequired vs Optional Vars
Some variables must exist for the app to run; others have sensible fallbacks. A helper for required values fails loudly when one is missing.
function required(name: string): string {
const v = process.env[name];
if (v === undefined) throw new Error("Missing env: " + name);
return v;
}Parsing Numbers
Numeric variables need conversion and validation, since parseInt can yield NaN. Wrap the parse so bad input is rejected immediately.
function num(name: string): number {
const n = Number(required(name));
if (Number.isNaN(n)) throw new Error(name + " is not a number");
return n;
}Parsing Booleans
Booleans come in as strings like "true". Normalize them explicitly rather than relying on truthiness of a non-empty string.
function bool(name: string, def = false): boolean {
const v = process.env[name];
if (v === undefined) return def;
return v === "true" || v === "1";
}Building the Typed Config
Assemble the parsed values into one object matching the Env interface. From here on, the rest of the app uses the typed config, never process.env directly.
const env: Env = {
PORT: num("PORT"),
NODE_ENV: required("NODE_ENV") as Env["NODE_ENV"],
DATABASE_URL: required("DATABASE_URL"),
DEBUG: bool("DEBUG"),
};Constraining String Unions
For variables with a fixed set of values, validate against that set so an unexpected value cannot slip through as the wrong literal type.
function oneOf<T extends string>(name: string, allowed: readonly T[]): T {
const v = required(name) as T;
if (!allowed.includes(v)) throw new Error(name + " invalid");
return v;
}Centralize Access
Export the single env object from one module. Every consumer imports it, gaining full typing and a single place to change parsing logic.
export const config = env;
// elsewhere: import { config } from "./config";Augmenting ProcessEnv (Optional)
You can declare module augmentation for NodeJS.ProcessEnv to type raw access, but a parsed config object is safer because it also validates and converts.
// declare global { namespace NodeJS { interface ProcessEnv { PORT: string } } }Why a Typed Config Object Wins
A parsed, validated config gives correct types (numbers, booleans, unions), guaranteed presence of required vars, and one import for the whole app, instead of scattered unsafe process.env reads.
Quick Check
Quick check on this lesson.
Recap
Declare a typed Env interface, then parse process.env with helpers that convert and validate (numbers, booleans, string unions) and fail on missing required vars. Export one typed config object so the app never touches raw process.env.
Frequently asked questions
Is the “Typing Environment Variables” lesson free?
Yes — the full text of “Typing Environment Variables” is free to read here on the web, and the TypeScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the TypeScript Academy course, upgrade to CoddyKit PRO.
What will I learn in “Typing Environment Variables”?
Give process.env a precise, validated type. You practise TypeScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start TypeScript Academy?
No prior experience is required. TypeScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Typing Environment Variables” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this TypeScript Academy lesson?
Yes. Every TypeScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Typing Environment Variables
- Schema-Validated Config
- Config Layering and Defaults
- Secrets and Type Safety