Search code examples
node.jstypescript

using process.env in TypeScript


How do I read node environment variables in TypeScript?

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 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.