/* Codeboosh */

Google Analytics TypeScript Class

I use TypeScript a lot and most clients these days want Google Analytics on their websites. Here’s a handy TypeScript class that I often use. It assumes that you have the events setup in Google Tag Manager.

class GoogleAnalyticsService {

    public static trackEvent(category: string, action: string, label: string) {

        if (typeof window !== 'undefined' && typeof dataLayer !== 'undefined' && category) {

            dataLayer.push({
                event: 'GAevent',
                eventCategory: category.toLowerCase(),
                eventAction: action.toLowerCase(),
                eventLabel: label.toLowerCase()
            });

        }

    }

    public static trackImpression(category: string, action: string, label: string) {

        if (typeof window !== 'undefined' && typeof dataLayer !== 'undefined' && category) {

            dataLayer.push({
                event: 'GAimpression',
                eventCategory: category.toLowerCase(),
                eventAction: action.toLowerCase(),
                eventLabel: label.toLowerCase()
            });

        }

    }

    public static trackSocial(socialNetwork: string, socialAction: string, socialTarget: string) {

        if (typeof window !== 'undefined' && typeof dataLayer !== 'undefined' && socialNetwork) {

            dataLayer.push({
                event: 'GAsocialInteraction',
                socialNetwork: socialNetwork.toLowerCase(),
                socialAction: socialAction.toLowerCase(),
                socialTarget: socialTarget.toLowerCase()
            });

        }

    }
}