Home > Software engineering >  ts-node compiler is not reading environment variables
ts-node compiler is not reading environment variables

Time:08-02

I'm not sure if any of you ever came across the same issue but I've got a problem with ts-node and environment variables and your help would be much appreciated!

ts-node is not reading the environment variables

What I'm trying to do here is basically just to run index.ts with ts-node. And this index.ts simply prints out one of the environment variables.

index.ts

import "dotenv/config";

const printEnv = (value: string) => {
  console.log(value);
};

printEnv(process.env.PASSWORD);

To make the environment variables available from index.ts, I created env.d.ts in which I defined the type of the variable.

env.d.ts

declare global {
  namespace NodeJS {
    interface ProcessEnv {
      PASSWORD: string;
    }
  }
}
export {}

I set up my tsconfig.json, package.json and .env files like below.

tsconfig.json

{
  "name": "ts-env",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "start": "nodemon src/index.ts"
  },
  "devDependencies": {
    "@types/node": "^18.6.1",
    "nodemon": "^2.0.19",
    "ts-node": "^10.9.1",
    "typescript": "^4.7.4"
  },
  "dependencies": {
    "dotenv": "^16.0.1"
  }
}

package.json

{
  "name": "ts-env",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "start": "nodemon src/index.ts"
  },
  "devDependencies": {
    "@types/node": "^18.6.1",
    "nodemon": "^2.0.19",
    "ts-node": "^10.9.1",
    "typescript": "^4.7.4"
  },
  "dependencies": {
    "dotenv": "^16.0.1"
  }
}

.env

PASSWORD=test0123

With this setup, VSCode is now able to show me the possible options whenever I type process.env. enter image description here

But it fails to compile whenever I try to run this application with ts-node, saying that process.env.PASSWORD could be undefined.

Here is the error log from ts-node.

TSError: ⨯ Unable to compile TypeScript:
src/index.ts:9:10 - error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
  Type 'undefined' is not assignable to type 'string'.

9 printEnv(process.env.PASSWORD);

I did fair amount of digging but unable to find a right solution for this issue. It would be much appreciated if you could point me in the right direction.

CodePudding user response:

The type for an environment variable is string | undefined, which makes sense because it can miss, either the entire .env file, or just that the variable is not in it.

The fix here is either to change your function definition to:

const printEnv = (value: string | undefined) => {
  console.log(value);
};

printEnv(process.env.PASSWORD);

Or tell TypeScript that the variable PASSWORD exist for sure with the ! mark, like so:

const printEnv = (value: string) => {
  console.log(value);
};

printEnv(process.env.PASSWORD!);
  • Related