using process.env in TypeScript using process.env in TypeScript typescript typescript

using process.env in TypeScript


Once you have installed @types/node in your project, you can tell TypeScript exactly what variables are present in your process.env:

environment.d.ts

declare global {  namespace NodeJS {    interface ProcessEnv {      GITHUB_AUTH_TOKEN: string;      NODE_ENV: 'development' | 'production';      PORT?: string;      PWD: string;    }  }}// If this file has no import/export statements (i.e. is a script)// convert it into a module by adding an empty export statement.export {}

Usage:

process.env.GITHUB_AUTH_TOKEN; // $ExpectType string

This method will give you IntelliSense, and it also takes advantage of string literal types.

Note: the snippet above is module augmentation. Files containing module augmentation must be modules (as opposed to scripts). The difference between modules and scripts is that modules have at least one import/export statement.

In order to make TypeScript treat your file as a module, just add one import statement to it. It can be anything. Even export {} will do.


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.


just add before use process.env.NODE_ENV follow lines:

declare var process : {  env: {    NODE_ENV: string  }}