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?
Documentation tags work in both TypeScript and JavaScript. The meaning is usually the same, or a superset, of the meaning of the tag given at jsdoc.app . The code below describes the differences and gives some example usage of each tag.
More on Functions Functions are the basic building block of any application, whether they’re local functions, imported from another module, or methods on a class. They’re also values, and just like other values, TypeScript has many ways to describe how functions can be called.
Specifying Type Arguments TypeScript can usually infer the intended type arguments in a generic call, but not always. For example, let’s say you wrote a function to combine two arrays: function combine < Type > (arr1: Type [], arr2: Type []): Type [] {
In TypeScript, generics are used when we want to describe a correspondence between two values. We do this by declaring a type parameter in the function signature: By adding a type parameter Type to this function and using it in two places, we’ve created a link between the input of the function (the array) and the output (the return value).
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
Depending on your tsconfig
, you might need to add it to the types
option.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With