Skip to content

Instantly share code, notes, and snippets.

@louishuyng
Created April 22, 2024 14:19
Show Gist options
  • Save louishuyng/2970d9a4be5c4b4c4ea53cf0b1908994 to your computer and use it in GitHub Desktop.
Save louishuyng/2970d9a4be5c4b4c4ea53cf0b1908994 to your computer and use it in GitHub Desktop.
Event Tracking With Typescript
const trackEvent = <T extends PendoEvents>(
event: T,
...args: T extends PendoEvents
? PendoData[T] extends null
? []
: [PendoData[T]]
: []
) => {
PendoTrackEvent.track({
window.pendo,
event,
data: args[0] || {},
});
}
trackEvent("example", { name: "Test" })
import { PendoEvents, TrackPayload } from "./types";
export class PendoTrackEvent {
public static track<Event extends PendoEvents>(
trackPayload: TrackPayload<Event>
) {
const { pendo, event, data } = trackPayload;
const eventName = this.formatEventName(event);
pendo.track(eventName, data);
console.log(`Pendo has tracked event ${eventName}`, data);
}
// For example, "user_logged_in" -> "User Logged In"
private static formatEventName(event: PendoEvents): string {
return event
.split("_")
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(" ");
}
}
// NOTE: For adding new pending event, you only need to work on PendoData
// By adding new key-value pair to PendoData, you can add new event
// Under PendoTrackEvent we can track the event by calling trackEvent method
// NOTE: event key inside PendoData is not the event name we use in Pendo
// For example: `regenius_click` will be replace as `Regenius Click` event in Pendo
export type PendoData = {
regenius_click: null; // No data needed
example_event: {
name: string;
};
};
export type PendoEvents = keyof PendoData;
export type TrackPayload<T extends PendoEvents = PendoEvents> = {
pendo: typeof window.pendo;
event: T;
data: PendoData[T] | {};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment