using process.env in TypeScript

Christophe Le Besnerais picture Christophe Le Besnerais · Jul 19, 2017 · Viewed 179.7k times · Source

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.

Answer

Karol Majewski picture Karol Majewski · Dec 30, 2018

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.