Practical Example: Typing process.env
What you'll learn: How to add type safety to environment variables by augmenting the global NodeJS.ProcessEnv interface.
The Problem with Untyped Environment Variables
By default, process.env in Node.js is typed as NodeJS.ProcessEnv, which is essentially an index signature allowing any string key to return string | undefined. This means TypeScript can't help you catch typos or missing variables:
// No autocomplete, no error if PORT is misspelled
const port = process.env.PROT; // Oops! Should be PORT
Using Declaration Merging to Extend ProcessEnv
You can use declaration merging to add strongly-typed properties to the global NodeJS.ProcessEnv interface. Create a .d.ts file (commonly env.d.ts or global.d.ts) and declare your specific environment variables:
// env.d.ts
declare global {
namespace NodeJS {
interface ProcessEnv {
NODE_ENV: 'development' | 'production' | 'test';
PORT: string;
DATABASE_URL: string;
API_KEY: string;
OPTIONAL_FEATURE?: string; // Optional var
}
}
}
export {};
The export {} forces this file into module scope, allowing the declare global to work properly.
Using Your Typed Environment Variables
Now process.env has autocomplete and type checking:
// config.ts
const config = {
port: parseInt(process.env.PORT), // TypeScript knows PORT exists
isProduction: process.env.NODE_ENV === 'production', // Literal union!
dbUrl: process.env.DATABASE_URL,
// TypeScript error if you mistype:
// apiKey: process.env.API_KEI // Error: Property 'API_KEI' doesn't exist
};
Key Takeaway: By merging interface declarations into the global NodeJS.ProcessEnv, you transform untyped environment variables into strongly-typed, autocomplete-friendly properties that catch configuration errors at compile time.