最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - typescript error accessing globalThis property - Stack Overflow

programmeradmin1浏览0评论

i am trying to access the globalThis property, but get the error:

Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature`.
// both getting...
if (!globalThis.foo) {}

// and setting...
globalThis.foo = 'bar

the only thing i can find online about this, refers to using window, and provides declarations to support it, but not for globalThis. anyone know how to support this?

i am trying to access the globalThis property, but get the error:

Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature`.
// both getting...
if (!globalThis.foo) {}

// and setting...
globalThis.foo = 'bar

the only thing i can find online about this, refers to using window, and provides declarations to support it, but not for globalThis. anyone know how to support this?

Share Improve this question edited Oct 4, 2020 at 15:08 brewster asked Oct 4, 2020 at 14:32 brewsterbrewster 4,5027 gold badges48 silver badges72 bronze badges 3
  • You should provide code that demonstrates the problem. – Wyck Commented Oct 4, 2020 at 14:35
  • @Wyck i added some example code, but i get the error literally doing anything with globalThis – brewster Commented Oct 4, 2020 at 15:10
  • For anyone trying to use it with a library: let cached = (global as any).mongoose – TechWisdom Commented May 6, 2024 at 20:24
Add a comment  | 

1 Answer 1

Reset to default 19

According to the globalThis documentation, it looks like the "right" way to do this is to declare a global var named foo. That will add to globalThis.

If your code is in global scope, then this will work:

var foo: string;

If your code is in a module, you need to wrap that in a global declaration:

export const thisIsAModule = true; // <-- definitely in a module

declare global {
    var foo: string;
}

After that, you should be able to access globalThis.foo as desired:

globalThis.foo = "bar"; // no error

Playground link to code

发布评论

评论列表(0)

  1. 暂无评论