patternjavascriptMajor
using process.env in TypeScript
Viewed 0 times
processtypescriptenvusing
Problem
How do I read node environment variables in TypeScript?
If i use
I have installed
If i use
process.env.NODE_ENV I have this error :Property 'NODE_ENV' does not exist on type 'ProcessEnv'I have installed
@types/node but it didn't help.Solution
There's no guarantee of what (if any) environment variables are going to be available in a Node process - the
Which means that
Alternatively, as jcalz pointed out in the comments, if you're using TypeScript 2.2 or newer, you can access indexable types like the one defined above using the dot syntax - in which case, your code should just work as is.
NODE_ENV variable is just a convention that was popularised by Express, rather than something built in to Node itself. As such, it wouldn't really make sense for it to be included in the type definitions. Instead, they define process.env like this:export interface ProcessEnv {
[key: string]: string | undefined
}Which means that
process.env can be indexed with a string in order to get a string back (or undefined, if the variable isn't set). To fix your error, you'll have to use the index syntax:let env = process.env["NODE_ENV"];Alternatively, as jcalz pointed out in the comments, if you're using TypeScript 2.2 or newer, you can access indexable types like the one defined above using the dot syntax - in which case, your code should just work as is.
Code Snippets
export interface ProcessEnv {
[key: string]: string | undefined
}let env = process.env["NODE_ENV"];Context
Stack Overflow Q#45194598, score: 89
Revisions (0)
No revisions yet.