Types You Don't Control 12 exercises

Modifying process.env Typing in TypeScript

Node.js introduces a global entity called process, which includes several properties that are typed with @types/node.

The env property is an object encapsulating all the environment variables that have been incorporated into the current running process. This can come in handy for feature fla

Loading exercise


00:00 Node adds in a global into JavaScript called process. And this is typed with types node as well. So we get node.js.process here. And what process does is it has a bunch of different properties on it. If we just access it, have a look at it, process.all sorts of things,

00:17 argv, current working directory, emit, et cetera. But the one I'm interested in now is env. Now, env represents an object containing all of the environment variables that have been injected into the current working process. So this means that if you have any kind of like, if you need to feature flag some stuff

00:37 or you need different environments to target different APIs, this would be the way to do it. Usually a platform will let you add an environment variable and this would appear on process.env, this object. Now, this is great, except that TypeScript doesn't know about anything that it can't see, right?

00:53 So anything external to the actual code that's here, it doesn't know what environment variables are going to be injected. So we need to find a way to tell it because currently my env var is just gonna be string or undefined. It knows that if you sort of access anything on here, well, sure, it might be in the global scope,

01:11 but it doesn't know, so it could be string or undefined. We need a way to tell TypeScript that certain environment variables will be there. Definitely, definitely, definitely. And we're going to need to modify the sort of global scope in order to do that. Now, this is a little different from when we did it with window because with window, you just had an interface on the global,

01:31 but I want you to notice that process is actually nodejs.process and env is nodejs.process.env here. So nodejs.processenv, this is the one. And what you'll see is if you do a little bit of deep diving

01:49 that nodejs is a namespace. And so you're going to need to go into the global scope, add in a namespace, which we know can merge with other namespaces, and then add an interface inside there. And you might need to do a little bit of kind of trial and error to find your way there, but that is the way to do it.

02:07 And you need to add myenv into there as a string. Good luck.