打字稿错误访问globalThis属性

时间:2020-10-04 14:32:35

标签: javascript typescript

我正在尝试访问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。有人知道如何支持吗?

1 个答案:

答案 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

Playground link to code