Generating TypeScript types for environment variables

1 min read

A type-safe approach to handling environment variables in TypeScript projects.

Generating TypeScript types for environment variables

Environment variables are a crucial part of any application, but they can be a source of runtime errors if not handled properly. Let's explore how to make them type-safe.

The Problem

// This could fail at runtime
const apiKey = process.env.API_KEY;

The Solution

Create a schema for your environment variables:

import { z } from "zod";

const envSchema = z.object({
    API_KEY: z.string(),
    DATABASE_URL: z.string().url(),
    PORT: z.string().transform(Number),
});

declare global {
    namespace NodeJS {
        interface ProcessEnv extends z.infer<typeof envSchema> {}
    }
}

Now TypeScript will help you catch errors before they happen!