node.js - 无法识别环境变量的 TypeScript 声明
问题描述
我在启动我的 node.js 服务器时尝试连接到 MongoDB。我的服务器在src/server.ts
,connectDB()
在src/config/db.ts
和我的.env
, 并且environment.d.ts
在根目录中。但是,当尝试连接到数据库时,它仍然说 my MONGO_URI
,声明 in .env
,是 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;
完整的错误代码:
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, {
我尝试dotenv.config()
在. 将鼠标悬停在 VSCode 中的环境变量上会显示. 所以我真的认为这是正确的设置,但我一定遗漏了一些东西。db.ts
server.ts
(property) NodeJS.ProcessEnv.MONGO_URI: string
解决方案
此错误可能是由于您的 tsconfig.json 文件规则造成的。很可能是由于"strictNullChecks": true
您可能已将此规则设置为true。有两个简单的解决方案:
- 像这样把这条规则设置为假
"strictNullChecks": false
。 - 或像这样
!
立即添加process.env.MONGO_URI
:process.env.MONGO_URI!
. 该符号!
确保您的打字稿转译器该值不会是undefined。
推荐阅读
- python - 一次用多个标记标记 test_
- ios - 如何使用 EXPO iOS StoreReview API?
- javascript - JavaScript 日期格式忽略时区
- r - 如何合并数据框中的行并合并单元格中的因子值
- rxjs - Rxjs 可观察,内部订阅需要很长时间,外部可观察在后续请求中首先执行
- python-3.x - 如何将数据帧的索引存储为新字符串?
- javascript - ajax 传单 setView (cityname or postalCode)
- c# - 通过 Url 从客户端访问 IIS 服务器上的图像 | ASP.NET
- python-3.x - 如何使用 statsmodel 推断时间序列模型以预测样本外未来值
- go - 查找 gitlab.com/company/project/.vscode 最新