我正在尝试在typescript中赋值自定义全局变量。我的项目结构如下:
- config/
- src/
- types/
- custom.d.ts
- index.ts
- package.json
- tsconfig.json里面的custom.d.ts文件是这样的:
declare global {
namespace NodeJS {
interface Global {
customvar: string
}
}
}
export default global;在我的tsconfig.json中
{
...,
"typeRoots": [
"types"
],
"types": [
"node"
]
}在我的index.ts中,当我尝试下面这样的东西并运行它时:
global.customvar = "test";它抛出错误:
index.ts:1:8 - error TS2339: Property 'customvar' does not exist on type 'Global & typeof globalThis'.我做错什么了?我的customvar甚至已经在自动补全中显示了:

我尝试了在网上可以找到的解决方案,但似乎没有解决我的问题。我错过了什么吗?任何解决方案/建议都将不胜感激。
发布于 2020-11-10 10:21:02
这个问题已经解决了。这个问题既不是来自typescript,也不是结构本身。但是,它来自ts-node。因为我使用ts-node来运行我的脚本,所以我的设置中缺少几个配置。
可以在这里找到解决方案:https://github.com/TypeStrong/ts-node#help-my-types-are-missing
https://stackoverflow.com/questions/64532005
复制相似问题