gtag function Typescript definition

Viewed 10830

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?

3 Answers

To expand on the answer by @thisismydesign.

Install:

yarn add -D @types/gtag.js

And it should detect it globally automatically. But if types is set in tsconfig.json, it probably won't. Either remove types from the config or add @types/gtag.js to it like so:

"types": ["cypress", "@testing-library/cypress", "@types/gtag.js"],

Also note that if this is added then any build directory may need deleting to stop things like linting from hanging.

To get my code to compile it required one more step than above..

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

Add to types in tsconfig.json

    "types": [..., "@types/gtag.js", ...]

Declare the function in the files that you want to use it

    declare let gtag: Function;
Related