在JavaScript中,我可以这样做:
something = 'testing';
然后在另一个文件中:
if (something === 'testing')
它将定义something
(只要它们是以正确的顺序调用的)。
我似乎不知道如何在TypeScript中做到这一点。
这就是我尝试过的。
在.d.ts文件中:
interface Window { something: string; }
然后在我的main.ts文件中:
window.something = 'testing';
然后在另一个文件中:
if (window.something === 'testing')
,这是可行的。但我希望能够去掉其中的 window.
部分,只想让我的成为全局的。有没有办法在TypeScript中做到这一点?
(如果有人感兴趣,我正在尝试为我的应用程序设置我的日志。我希望能够从任何文件调用log.Debug
,而不必导入和创建对象。)
发布于 2017-04-20 23:31:46
在.d.ts
定义文件中
type MyGlobalFunctionType = (name: string) => void
如果在浏览器中工作,则将成员添加到浏览器的窗口上下文中:
interface Window {
myGlobalFunction: MyGlobalFunctionType
}
NodeJS也有同样的想法:
declare module NodeJS {
interface Global {
myGlobalFunction: MyGlobalFunctionType
}
}
现在你声明了root变量(它将实际存在于窗口或全局)
declare const myGlobalFunction: MyGlobalFunctionType;
然后在一个常规的.ts
文件中,但作为副作用导入,您实际上实现了它:
global/* or window */.myGlobalFunction = function (name: string) {
console.log("Hey !", name);
};
最后在代码库的其他地方使用它,使用以下两种方法之一:
global/* or window */.myGlobalFunction("Kevin");
myGlobalFunction("Kevin");
发布于 2019-07-11 16:36:01
globalThis就是未来。
首先,TypeScript文件有两种scopes
全局作用域
如果您的文件没有任何全局作用域import
或export
行,则此文件将在全局作用域中执行,以确保其中的所有声明在此文件外部可见。
所以我们会像这样创建全局变量:
// xx.d.ts
declare var age: number
// or
// xx.ts
// with or without declare keyword
var age: number
// other.ts
globalThis.age = 18 // no error
所有的魔法都来自于
var
。用let
或const
替换var
将不起作用。
模块作用域
如果您的文件具有任何全局import
行或export
,则此文件将在其自身的范围内执行,我们需要通过declaration-merging扩展。
// xx[.d].ts
declare global {
var age: number;
}
// other.ts
globalThis.age = 18 // no error
您可以在official docs
中查看有关模块的更多信息
发布于 2019-07-11 16:10:44
这就是我修复它的方法:
步骤:
declare global {
namespace NodeJS {
interface Global {
Config: {}
}
}
}
export default global;
"typeRoots": ["src/types/custom.d.ts" ]
console.log(global.config)
备注:
希望这能有所帮助!
谢谢
https://stackoverflow.com/questions/38906359
复制相似问题