Google analytics 4 with typescript

Viewed 967

I want to create a function that triggers a GA4 measurement only when the visitor agrees. I created it as follows:

document.querySelector('.cookie').addEventListener('click', function(){

        var ga = document.createElement('script')
        ga.type = 'text/javascript'
        ga.async = true
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.googletagmanager.com/gtag/js?id=UA-XXXXXX-X'
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);


        let gat = window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
                gtag('js', new Date());
                gtag('config', 'UA-XXXXXX-X');
                setCookie('cookie','1',365);
        return false;
    })

The problem is that typescript reports errors: Property 'dataLayer' does not exist on type 'Window & typeof globalThis a gtag - Expected 0 arguments, but got 2.

I've tried various tutorials, installed @types/gtag.js, but the errors persist. Can you advise me what I'm doing wrong? Thank you

1 Answers
  1. Adding a script in a click listener may be dangerous.

  2. Looks like your problems have nothing to do with GA or gtag. First error just indicates that you're surfacing dataLayer incorrectly. Looks like it's typescript's protection. You should have something like described here: Datalayer.push with Typescript in Angular 6

  3. What you do to the gtag function is confusing. Looks like you're declaring gtag() here:

function gtag(){dataLayer.push(arguments);}

And as we can see, you mean for it to not accept arguments, but you're trying to call it and pass two arguments into it.

  1. You don't ever need to declare gtag(). It's supposed to be taken care of by the library that you're trying to load. But it looks like you're not even waiting for the code to load, you're trying to use gtag right away...

  2. I don't see where you define the arguments var that you're attempting to push into the DL. I'm afraid it may cause issues too.

There are many issues with that code, but nothing really relates to analytics. It's all general front-end dev issues.

Related