我正在尝试访问globalThis
属性,但收到错误消息:
Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature`.
// both getting...
if (!globalThis.foo) {}
// and setting...
globalThis.foo = 'bar
我在网上可以找到的唯一内容是使用window
,并提供了支持它的声明,但没有针对globalThis。有人知道如何支持吗?
答案 0 :(得分:2)
根据the globalThis
documentation,看来这样做的“正确”方法是声明一个名为var
的全局foo
。这将添加到globalThis
。
如果您的代码在全局范围内,那么它将起作用:
var foo: string;
如果您的代码在模块中,则需要将其包装在global
声明中:
export const thisIsAModule = true; // <-- definitely in a module
declare global {
var foo: string;
}
之后,您应该可以根据需要访问globalThis.foo
:
globalThis.foo = "bar"; // no error