lpritchard
lpritchard

Reputation: 141

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.

Upvotes: 8

Views: 11669

Answers (2)

Israel kusayev
Israel kusayev

Reputation: 1001

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 {};

Upvotes: 11

Shakir Aqeel
Shakir Aqeel

Reputation: 352

This error may be due to your tsconfig.json file rules. Most probably due to "strictNullChecks": true you may have put this rule to true. There are two simple solutions:

  1. put this rule to false like this "strictNullChecks": false.
  2. Or add ! immediately after process.env.MONGO_URI like this: process.env.MONGO_URI!. The symbol ! insures your typescript transpiler the value will not be undefined.

Upvotes: 6

Related Questions