'gtag function Typescript definition

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 1:[1]

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

Solution 2:[2]

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.

Solution 3:[3]

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;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 JAA