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

lpr*_*ard 7 environment-variables mongodb node.js typescript

我在启动 Node.js 服务器时尝试连接到 MongoDB。我的服务器位于src/server.tsconnectDB()src/config/db.tsmy .env、 以及environment.d.ts根目录中。然而,当尝试连接到数据库时,它仍然说 my MONGO_URI,在 中声明.env,是 type string | undefined

\n

environment.d.ts:

\n
declare namespace NodeJS {\n  export interface ProcessEnv {\n    PORT?: string;\n    NODE_ENV: 'development' | 'production';\n    MONGO_URI: string;\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

src/server:

\n
import dotenv from 'dotenv';\nimport express from 'express';\nimport connectDB from './config/db';\n\ndotenv.config({ path: '../.env' });\nconnectDB();\nconst app = express();\n\n.....\n
Run Code Online (Sandbox Code Playgroud)\n

src/config/db.ts:

\n
import mongoose from 'mongoose';\n\nconst connectDB = async () => {\n  try {\n    const conn = await mongoose.connect(process.env.MONGO_URI, {\n      useUnifiedTopology: true,\n      useNewUrlParser: true,\n      useCreateIndex: true,\n    });\n\n    console.log(`MongoDB connected: ${conn.connection.host}`);\n  } catch (error) {\n    console.error(`ERROR: ${error.message}`);\n    process.exit(1);\n  }\n};\n\nexport default connectDB;\n
Run Code Online (Sandbox Code Playgroud)\n

完整错误代码:

\n
TSError: \xe2\xa8\xaf Unable to compile TypeScript:\nsrc/config/db.ts:5:41 - error TS2769: No overload matches this call.\n  Overload 1 of 3, '(uri: string, callback: (err: CallbackError) => void): void', gave the following error.\n    Argument of type 'string | undefined' is not assignable to parameter of type 'string'.\n      Type 'undefined' is not assignable to type 'string'.\n  Overload 2 of 3, '(uri: string, options?: ConnectOptions | undefined): Promise<typeof import("mongoose")>', gave the following error.\n    Argument of type 'string | undefined' is not assignable to parameter of type 'string'.\n      Type 'undefined' is not assignable to type 'string'.\n\n5     const conn = await mongoose.connect(process.env.MONGO_URI, {\n
Run Code Online (Sandbox Code Playgroud)\n

我尝试在 中声明它时声明dotenv.config()insidedb.ts并删除路径选项server.ts。将鼠标悬停在 VSCode 中的环境变量上会显示(property) NodeJS.ProcessEnv.MONGO_URI: string. 所以我真的认为这是正确的设置,但我一定错过了一些东西。

\n

Isr*_*yev 7

尝试将其添加到global.d.ts文件中,如下所示

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

export {};
Run Code Online (Sandbox Code Playgroud)


Sha*_*eel 6

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

  1. 像这样将此规则设置为false"strictNullChecks": false
  2. 或者像这样!立即添加: 。该符号确保您的打字稿转译器的值不会是undefinedprocess.env.MONGO_URIprocess.env.MONGO_URI!!

  • 这确实解决了错误,但现在它仍然说我传递的参数是“未定义”,所以我不知道为什么我的“.env”变量都不存在,即使我已经声明了它们。编辑:将我的服务器移至根目录并更改路径,现在可以使用。感谢你的帮助。 (3认同)