Environment Variables in TypeScript

Environment variables are a universal mechanism for conveying configuration information to programs. Let’s look at how to set, get, and list environment variables in TypeScript.

import * as process from 'process';

// To set a key/value pair, use process.env
// To get a value for a key, use process.env
// This will return undefined if the key isn't present in the environment
process.env.FOO = '1';
console.log('FOO:', process.env.FOO);
console.log('BAR:', process.env.BAR);

// Use Object.entries(process.env) to list all key/value pairs in the environment
// This returns an array of [key, value] pairs
// Here we print all the keys
console.log();
for (const [key, _] of Object.entries(process.env)) {
    console.log(key);
}

Running the program shows that we pick up the value for FOO that we set in the program, but that BAR is undefined.

$ ts-node environment-variables.ts
FOO: 1
BAR: undefined

PATH
SHELL
...
FOO

The list of keys in the environment will depend on your particular machine.

If we set BAR in the environment first, the running program picks that value up.

$ BAR=2 ts-node environment-variables.ts
FOO: 1
BAR: 2
...

In TypeScript, we use the process.env object to interact with environment variables. This object is part of the Node.js process module, which is automatically available in Node.js environments.

To set an environment variable, we can directly assign a value to a property of process.env. To get an environment variable, we can access it as a property of process.env.

To list all environment variables, we use Object.entries(process.env), which gives us an array of key-value pairs that we can iterate over.

Remember that when working with environment variables in TypeScript, you’re typically doing so in a Node.js environment. If you’re using TypeScript in a browser environment, you won’t have access to process.env and will need to use a different approach to handle configuration.