gpt4 book ai didi

javascript - 访问 globalThis 属性的 typescript 错误

转载 作者:行者123 更新时间:2023-12-04 08:48:24 27 4
gpt4 key购买 nike

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

最佳答案

根据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

关于javascript - 访问 globalThis 属性的 typescript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64195920/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com