I am currently working on implementing a Google Tag loading script using TypeScript.
const GTAG_ID = 'ID';
const script = document.createElement('script');
script.src = `https://www.googletagmanager.com/gtag/js?id=${GTAG_ID}`;
script.async = true;
document.head.appendChild(script);
window.dataLayer = window.dataLayer || [];
function gtag() {
window.dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', GTAG_ID, { send_page_view: false });
gtag('event', 'page_view');
The above code successfully executes and triggers the gtag event. However, if I attempt to add some level of typing to the gtag function, the following code snippet would be the solution.
function gtag(...args: Array<unknown>) {
window.dataLayer.push(args);
}
Strangely, after implementing this typed approach, the gtag event stops firing. There are no console errors, and whether I use spread syntax on the arguments or not, the issue persists. This has left me puzzled and wondering why this modification does not function as expected.