首页 > 解决方案 > 无法识别环境变量的 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.tsserver.ts(property) NodeJS.ProcessEnv.MONGO_URI: string

标签: node.jsmongodbtypescriptenvironment-variables

解决方案


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

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

推荐阅读