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.
Running the program shows that we pick up the value for FOO
that we set in the program, but that BAR
is undefined.
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.
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.