The node.js process.env
object seems to process property assignment differently than regular JavaScript objects. How can I get the process.env
object to act like a regular object in this case?
Below is sample code illustrating the different assignment behavior. For some reason assigning undefined
to a property results in a string type (only for process.env
):
function demo(description, dict) {
console.log(description);
dict.A = undefined;
console.log('typeof dict.A: ' + typeof dict.A + '\n');
}
demo('Passing empty object:', {});
demo('Passing process.env:', process.env);
The resulting output is different depending on if an empty object {}
or the process.env
object was passed:
$ node test.js Passing empty object: typeof dict.A: undefined Passing process.env: typeof dict.A: string
The one notable difference with the process. env object, is that every key and value will always be a string.
So yeah its pretty low level its casted back and forth, because the process is an global variable and its always stored as string.
In order to make TypeScript treat your file as a module, just add one import statement to it. It can be anything. Even export {} will do. I get a TS error here, "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations." And this is my react-app-env.
The process.env
object forces all of its properties to be of type string, since environment variables must always be strings. I'm not entirely sure on your purpose, but maybe you could try one of these as a workaround:
Copy the process.env
object into a new object, which will then behave normally:
envCopy = {};
for (e in process.env) envCopy[e] = process.env[e];
Assign ''
to a property instead if you wish it to be 'blank'
process.env.A = '';
Which will then return false when you treat it as a boolean
if (process.env.A) {
...
}
Or as Jonathan Lonowski points out, you can also delete
the key from process.env
delete process.env.A;
Hope this helps
This is occurring because process.env
forces all of its values to String
:
process.env.A = undefined;
console.log(process.env.A); // 'undefined' (note the quotes)
process.env.A = true;
console.log(process.env.A); // 'true'
console.log(typeof process.env.A); // 'string'
If you need to remove an environment variable, you'll have to delete
it:
function demo(description, dict) {
console.log(description);
delete dict.A;
console.log('typeof dict.A: ' + typeof dict.A + '\n');
}
demo('Passing process.env:', process.env);
// Passing process.env:
// typeof dict.A: undefined
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With