I am trying to make a Google Tag loading script work, using TS.
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 code above works and the gtag event fires. However, if I want the gtag function to be typed (somewhat), this would be the approach.
function gtag(...args: Array<unknown>) {
window.dataLayer.push(args);
}
However, when using this approach, the gtag event does not fire. No console errors. It doesn't matter if I spread the second args or not. This leaves me scratching my head. Why does this not work?
It's probably a type issue since Google expects following format for events:
dataLayer.push({'event': 'event_name'});