'TypeScript declarations for environment variables not being recognized

I am trying to connect to MongoDB when starting my node.js server. My server is in src/server.ts, connectDB() is in src/config/db.ts and my .env, and environment.d.ts are in the root directory. However, when trying to connect to the DB it still says my MONGO_URI, declared in .env, is of type string | undefined.

environment.d.ts:

declare namespace NodeJS {
  export interface ProcessEnv {
    PORT?: string;
    NODE_ENV: 'development' | 'production';
    MONGO_URI: string;
  }
}

src/server:

import dotenv from 'dotenv';
import express from 'express';
import connectDB from './config/db';

dotenv.config({ path: '../.env' });
connectDB();
const app = express();

.....

src/config/db.ts:

import mongoose from 'mongoose';

const connectDB = async () => {
  try {
    const conn = await mongoose.connect(process.env.MONGO_URI, {
      useUnifiedTopology: true,
      useNewUrlParser: true,
      useCreateIndex: true,
    });

    console.log(`MongoDB connected: ${conn.connection.host}`);
  } catch (error) {
    console.error(`ERROR: ${error.message}`);
    process.exit(1);
  }
};

export default connectDB;

Full error code:

TSError: ⨯ Unable to compile TypeScript:
src/config/db.ts:5:41 - error TS2769: No overload matches this call.
  Overload 1 of 3, '(uri: string, callback: (err: CallbackError) => void): void', gave the following error.
    Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
      Type 'undefined' is not assignable to type 'string'.
  Overload 2 of 3, '(uri: string, options?: ConnectOptions | undefined): Promise<typeof import("mongoose")>', gave the following error.
    Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
      Type 'undefined' is not assignable to type 'string'.

5     const conn = await mongoose.connect(process.env.MONGO_URI, {

I tried declaring the dotenv.config() within db.ts and removing the path option when declaring it in server.ts. Hovering over the environment variable in VSCode shows (property) NodeJS.ProcessEnv.MONGO_URI: string. So I really thought this was setup right but I must be missing something.



Solution 1:[1]

Try to add it inside global.d.ts file like this

declare global {
    namespace NodeJS {
        interface ProcessEnv {
             PORT?: string;
             NODE_ENV: 'development' | 'production';
             MONGO_URI: string;
        }
    }
}

export {};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Israel kusayev