Node.js 无法识别环境变量的TypeScript声明

Node.js 无法识别环境变量的TypeScript声明,node.js,mongodb,typescript,environment-variables,Node.js,Mongodb,Typescript,Environment Variables,启动node.js服务器时,我正在尝试连接到MongoDB。我的服务器位于src/server.ts,connectDB()位于src/config/db.ts中,我的.env和environment.d.ts位于根目录中。但是,当尝试连接到DB时,它仍然会显示在.env中声明的myMONGO_URI,其类型为string |未定义 environment.d.ts: declare namespace NodeJS { export interface ProcessEnv { P

启动node.js服务器时,我正在尝试连接到MongoDB。我的服务器位于
src/server.ts
connectDB()
位于
src/config/db.ts
中,我的
.env
environment.d.ts
位于根目录中。但是,当尝试连接到DB时,它仍然会显示在
.env
中声明的my
MONGO_URI
,其类型为
string |未定义

environment.d.ts

declare namespace NodeJS {
  export interface ProcessEnv {
    PORT?: string;
    NODE_ENV: 'development' | 'production';
    MONGO_URI: string;
  }
}
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;
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

declare namespace NodeJS {
  export interface ProcessEnv {
    PORT?: string;
    NODE_ENV: 'development' | 'production';
    MONGO_URI: string;
  }
}
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, {
t错误:⨯ 无法编译类型脚本:
src/config/db.ts:5:41-错误TS2769:没有与此调用匹配的重载。
重载第1个,共3个,'(uri:string,callback:(err:CallbackError)=>void:void',出现以下错误。
“string | undefined”类型的参数不能分配给“string”类型的参数。
类型“未定义”不可分配给类型“字符串”。
重载3中的第2个,'(uri:string,options?:ConnectOptions | undefined):Promise'给出了以下错误。
“string | undefined”类型的参数不能分配给“string”类型的参数。
类型“未定义”不可分配给类型“字符串”。
5 const conn=wait mongoose.connect(process.env.MONGO_URI{

我尝试在
db.ts
中声明
dotenv.config()
,并在
server.ts
中声明时删除路径选项。将鼠标悬停在VSCode中的环境变量上会显示
(属性)NodeJS.ProcessEnv.MONGO_URI:string
。所以我真的认为这是正确的设置,但我肯定遗漏了什么。

此错误可能是由于您的tsconfig.json文件规则造成的。最可能是由于
“strictNullChecks”:true
您可能已将此规则设置为true。 有两个简单的解决方案:

  • 将此规则设置为false如下
    “strictNullChecks”:false
  • 或者在
    process.env.MONGO\u URI
    之后立即添加
    ,如下所示:
    process.env.MONGO\u URI!
    。符号
    确保您的打字脚本传输程序不会未定义该值

  • 这确实绕过了错误,但是现在它仍然说我传递的参数是未定义的,所以我不知道为什么我的
    .env
    变量都不存在,即使我已经声明了它们。编辑:将我的服务器移到根目录并更改了路径,现在可以工作了。感谢您的帮助。欢迎您。