Using process.env to access environment variables in TypeScript is a common approach, especially in Node.js environments. Environment variables are typically used to store application configuration, such as database connection information and external API keys, which contain sensitive information. This avoids hardcoding values directly into the code, enhancing the application's security and flexibility.
1. Install Required Dependencies
First, ensure your project has the TypeScript definition files for the node type installed, enabling TypeScript to understand Node.js-specific types such as process:
bashnpm install --save-dev @types/node
2. Configure tsconfig.json
Ensure your tsconfig.json includes the corresponding type definition settings:
json{ "compilerOptions": { "types": ["node"] } }
3. Use process.env
In TypeScript files, you can directly access environment variables through process.env. For example, accessing the environment variable named DATABASE_URL:
typescriptconst databaseUrl: string | undefined = process.env.DATABASE_URL;
Here, we define a variable databaseUrl with type string | undefined, because accessing process.env.DATABASE_URL returns undefined if the environment variable is not set.
4. Enhance Type Safety
To enhance the robustness and maintainability of the code, you can create a function to manage environment variable access and provide type safety:
typescriptfunction getEnvVar(key: string): string { const value = process.env[key]; if (value === undefined) { throw new Error(`Environment variable ${key} is not set.`); } return value; } // Using the function to retrieve environment variables const databaseUrl: string = getEnvVar('DATABASE_URL');
This approach helps quickly identify issues when environment variables are not properly set, avoiding difficult-to-trace errors during application runtime.
5. Manage Environment Variables
In actual projects, to manage environment variables across different environments (such as development, testing, and production), you might use libraries like dotenv to load environment variables from .env files:
bashnpm install dotenv
Then, configure dotenv in your project's entry file:
typescriptimport * as dotenv from "dotenv"; dotenv.config();
This allows you to manage your environment variables in the .env file and access them via process.env in TypeScript code.
Summary
Using process.env to access and manage environment variables in TypeScript is an efficient and secure method. By properly configuring and writing type-safe code, you can effectively enhance the application's security and maintainability.