【问题标题】:Declare process var in global declare typescript .d.ts在全局声明 typescript .d.ts 中声明进程变量
【发布时间】:2022-01-15 15:22:32
【问题描述】:

我知道设置 .env 类型,我们在 .d.ts 中编写这段代码:

  var process: {
   env: {
      MONGO_DB_URL: string;
    }
  }

但是如果我在全局声明中这样做,像这样:

declare global {
  var process: {
   env: {
      MONGO_DB_URL: string;
    }
  }
  module Express {
    export interface Request {
      decodedToken: DecodedToken;
    }
    export interface Application {
      io: Server;
      sessionQIDtoSocketMap: Record<string, string>;
    }
  }
}

它给了我这个错误:

var process: globalThis.NodeJS.Process
Subsequent variable declarations must have the same type.  Variable 'process' must be of type 'Process', but here has type '{ env: { MONGO_DB_URL: string; }; }'.ts(2403)
globals.d.ts(44, 13): 'process' was also declared here.

如果我这样做:

declare var process: {
  env: {
    MONGO_DB_URL: string;
  };
};
declare global {
  module Express {
    export interface Request {
      decodedToken: DecodedToken;
    }
    export interface Application {
      io: Server;
      sessionQIDtoSocketMap: Record<string, string>;
    }
  }
}

错误然后消失,但打字稿仍然没有注册类型

【问题讨论】:

    标签: node.js typescript .d.ts


    【解决方案1】:

    不久前我遇到了同样的问题。像这样引用我的 .env 变量解决了我的问题

    const MONGODB_URL = process.env["MONGO_DB_URL"];
    

    编辑

    这就是我最终做的,比我之前的答案略好。在 globals.d.ts 中:

    declare namespace NodeJS {
      interface ProcessEnv {
       MONGO_DB_URL: string
       //etc...
      }
    }
    

    然后只引用 .env 变量,就像使用点符号之前一样。你应该得到智能感知

    如果有declare global,那么代码应该是:

    declare global {
      namespace NodeJS {
        export interface ProcessEnv {
          JWT_SECRET: string;
        }
      }
    }
    

    【讨论】:

    • 我也试过这个,但它不是类型安全的。我花了一周时间调试代码只是为了发现我试图访问“JWT_TOKEN_SECRET”而不是“JWT_SECRET”。即使是至少可以帮助我自动完成环境变量的配置也可以工作。
    • @omar 试试我更新后的答案,可能对你更有效
    • 试过了,没用。我根据您的代码找到了正确的解决方案。感谢您发布此 sn-p。
    猜你喜欢
    • 2017-07-25
    • 2020-02-10
    • 2019-07-27
    • 1970-01-01
    • 2013-08-12
    • 1970-01-01
    • 2019-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多