網站搜尋

node.js - TypeScript 對環境變數的聲明未被識別


我正在嘗試在啟動我的 node.js 伺服器時連接到 MongoDB。我的伺服器位於 src/server.ts,connectDB() 位於 src/config/db.ts,而我的 .env 和 environment.d.ts 位於根目錄中。然而,當嘗試連接到資料庫時,它仍然顯示我在 .env 中聲明的 MONGO_URI 類型為 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;

完整錯誤代碼:

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, {

我嘗試在 db.ts 中宣告 dotenv.config(),並在 server.ts 中宣告它時移除 path 選項。在 VSCode 中將滑鼠移到環境變數上會顯示 (property) NodeJS.ProcessEnv.MONGO_URI: string。所以我真的以為設定是正確的,但我一定漏掉了什麼。

答案#1

試著像這樣將它添加到 global.d.ts 檔案中

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

export {};

答案#2

此錯誤可能是由於您的 tsconfig.json 文件規則引起的。最有可能是因為 "strictNullChecks": true 您可能將此規則設置為 true。有兩個簡單的解決方法:

  1. 把這個規則設為 false,像這樣 "strictNullChecks": false。
  2. 或者馬上在 process.env.MONGO_URI 後面加上 !,像這樣:process.env.MONGO_URI!。符號 ! 確保你的 TypeScript 轉譯器該值不會是 undefined。