If I want to use process.env.NODE_ENV I first have to create a new environment.d.ts, declare the interfaxe and export an empty object just so the typescript compiler is satisfied. It sometimes just adds too much boilerplate.
If I want to use process.env.NODE_ENV I first have to create a new environment.d.ts, declare the interfaxe and export an empty object just so the typescript compiler is satisfied. It sometimes just adds too much boilerplate.
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.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.
https://www.typescriptlang.org/docs/handbook/release-notes/t...
// v is any or unknown
if (typeof v !== "string") {
throw new Error("oops")
}
// v is now string
You can’t get runtime type correctness by deceiving typescript into it.https://www.npmjs.com/package/@types/node
(ETA: It's mentioned in the StackOverflow and they still add an extra definition on top of it, but the env in the types today is a Record and you don't have to do it, you just won't get auto-completion on the names.)