【问题标题】:cannot access global variable directly without referring global typescript不引用全局打字稿就无法直接访问全局变量
【发布时间】:2022-01-15 08:52:28
【问题描述】:

我正在尝试创建一个可以跨文件访问的全局变量, 下面是代码

global.d.ts

declare module NodeJS {
interface Global {
  log: any;
 }
}

declare var log:any

index.ts

global.log = "Hello World"
console.log(global.log)//this Works
console.log(log) //this doesn't

tsconfig.json

 {


"compilerOptions": {                        
    "target": "es6",                         
    "module": "commonjs",                           
    "outDir": "./dist",                             
    "rootDir": "./src",                             
    "strict": true,
    "moduleResolution": "node",
    "esModuleInterop": true,    
    "noImplicitAny": false 
  }
}

package.json

{
  "name": "boilerplate",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "ts-node ./src/index.ts",
    "dev": "nodemon ./src/index.ts",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/config": "^0.0.40",
    "@types/express": "^4.17.13",
    "@types/winston": "^2.4.4",
    "nodemon": "^2.0.15",
    "ts-node": "^10.4.0",
    "typescript": "^4.5.2"
  },
  "dependencies": {
    "@types/node": "^16.11.12",
    "config": "^3.3.6",
    "dotenv": "^10.0.0",
    "express": "^4.17.1",
    "mongoose": "^6.1.0",
    "winston-daily-rotate-file": "^4.5.5"
  }
}

但出于某种原因

它给了我以下错误

TS2304:找不到名称“日志”。

【问题讨论】:

    标签: node.js typescript typescript-typings


    【解决方案1】:

    抱歉,但我很确定 global 不是这样工作的。如果它真的像这样工作,它可能会导致一些非常不可预测的行为。

    【讨论】:

    • 这可能是评论而不是答案。
    • @VimalPatel 我需要 50 声望才能发表评论
    猜你喜欢
    • 1970-01-01
    • 2012-11-28
    • 1970-01-01
    • 2014-01-17
    • 2014-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多