3 ms·
Don't do this! What TS is trying to tell you is that this variable may not have been set in the environment, and thus it's value inside of the program will eval
by lobstrosity420 5y ago
Don't do this! What TS is trying to tell you is that this variable may not have been set in the environment, and thus it's value inside of the program will evaluate to `undefined`.
What you are doing when you create the environment.d.ts file is forcing the transpiler to assume the variable will have been set, which is not really true. The program may still end up being executed in an environment in which the variable was not set.
Instead, what I like to do is create a config file in your project where you export an object containing all configuration values for your project. There, you can set default values for variables coming from the environment. In this way, you guarantee a value will be present for the execution of your program:
export const config = {
dbConnectionString: process.env.DB_CONNECTION || 'localhost:27017',
nodeEnv: process.env.NODE_ENV || 'development',
}
Remember that the NodeJS runtime guarantees the setting of no environment variables. The NODE_ENV variable is simply a convention that was started by express.
- capableweb 5y ago> Remember that the NodeJS runtime guarantees the setting of no environment variables. The NODE_ENV variable is simply a convention that was started by express. You're right that the runtime itself doesn't guarantee any env vars. I'm not sure who used it first, but npm also sets NODE_ENV (and some other env vars I think) in its different lifecycles, depending on if you provide the --production/--no-production flag when running it. But not sure if that came after or before express started using it.
- zumu 5y agoStuff like `dbConnectionString: process.env.DB_CONNECTION || 'localhost:27017'` is a good way to boot your app with the wrong environment variables and potentially cause security issues. I'd advise to make sure your app doesn't start or deploy if expected env vars aren't set.
- lobstrosity420 5y agoIf you do have some environment variable for which no safe fallback value may exist, you can implement that logic in the config file also. I was just giving a cursory example ;)
- gmac 5y agoDon’t forget the nullish coalescing operator, ??, which is probably nicer than using || here. https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html https://www.typescriptlang.org/docs/handbook/release-notes/t...
- lobstrosity420 5y agoYou're right, that is a much better choice for this situation!