尽管位于environment.d.ts中,打字稿仍将process.env变量识别为未定义

blu*_*lub 5 node.js typescript

我的印象是,将环境变量添加到environment.d.ts 将确保它们具有正确的类型。

我有 @types/node 作为开发依赖项,并且有一个包含以下内容的environment.d.ts

declare global {
  namespace NodeJS {
    interface ProcessEnv {
      DATABASE_URL: string;
    }
  }
}

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

但是,当我尝试使用 DATABASE_URL 时,例如

import PgPromise from "pg-promise";
const db = PgPromise()(process.env.DATABASE_URL || "");
Run Code Online (Sandbox Code Playgroud)

我仍然收到错误

error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string | IConnectionParameters<IClient>'.
Type 'undefined' is not assignable to type 'string | IConnectionParameters<IClient>'.
Run Code Online (Sandbox Code Playgroud)

有什么方法可以确保 DATABASE_URL 是字符串类型,而不是字符串 | 不明确的?我错过了什么吗?

blu*_*lub 9

该错误来自于我使用 ts-node 的事实。

我使用的是nodemon/ts-node,ts-node使用files/include/exclusive来确定要监视哪些文件。因为我没有指定这些,所以它无法检测到我的文件。

我通过添加修复了它

{
  ...,
  "ts-node": {
    "files": true
  },
  "include": ["src/**/*.ts", "environment.d.ts"]
}
Run Code Online (Sandbox Code Playgroud)

到我的 tsconfig.json