gtag function Typescript definition

Issue

I use original Javascript function

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

then got error: error TS2554: Expected 0 arguments, but got 3. when used like this:

gtag('event', 'page_view', { send_to: 'xxxx' })
I used // @ts-ignore as a workaround and it works: I see traffic in Google analytics. I want to do it properly without workarounds and I tried to replace gtag function like this:

function gtag(...args: any) {
  window.dataLayer.push(args)
}

and some other variants but it did not work. I see that window.dataLayer items now contain array instead of Object or Arguments.

Or better is there some existing gtag wrapper something similar to react-gtm or react-ga but for gtagjs?

Solution

You can install @types/gtag.js. See https://github.com/DefinitelyTyped/DefinitelyTyped/tree/4d4da2106dcd54af4a0ddeb5e0360f322fd8a5bf/types/gtag.js

yarn add -D @types/gtag.js

or

npm install --save-dev @types/gtag.js

Answered By – thisismydesign

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.