typescriptglobaladsensewindow-object

How to add "adsbygoogle" AdSense property to the "window" global object in Typescript?


I have a component that renders an <AdSense/> ad unit on my web app.

In index.html I have the following AdSense tag:

<script data-ad-client="XXXXXX" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

This script probably injects the adsbygoogle property to the window object.

But on my component, I have to use that property like this:

useEffect(()=>{
  (window.adsbygoogle = window.adsbygoogle || []).push({});
},[]);

This was fine when my project was in JavaScript, but now that I've switched to Typescript, I'm getting the following error:

ERROR in src/components/ads/AdSenseBanner.tsx:74:13
TS2339: Property 'adsbygoogle' does not exist on type 'Window & typeof globalThis'.

enter image description here

How can I declare this property to make Typescript understand what it is?


What I've tried:

I've created a d.ts for global declaration.

AMBIENT.d.ts

The following does not work.

declare const adsbygoogle: {[key: string]: unknown}[];

The following seems to work (as far as getting rid of the error). But it triggers a new error:

declare var adsbygoogle: {[key: string]: unknown}[];

enter image description here


Solution

  • The following article helped my to find a solution to this:

    https://mariusschulz.com/blog/declaring-global-variables-in-typescript

    AMBIENT.d.ts

    interface Window {
      adsbygoogle: {[key: string]: unknown}[]
    }
    

    From that article:

    Augmenting the Window Interface

    Lastly, you can use TypeScript's interface declaration merging to let the compiler know that it can expect to find a property named INITIAL_DATA on the Window type and therefore the window object. To do that, you'll need to define an interface named Window with a property named INITIAL_DATA:

    enter image description here

    TypeScript will merge this interface definition together with the Window interface defined in lib.dom.d.ts, resulting in a single Window type. Now, the following assignment will no longer produce a type error:

    enter image description here