Created
April 22, 2024 14:19
-
-
Save louishuyng/2970d9a4be5c4b4c4ea53cf0b1908994 to your computer and use it in GitHub Desktop.
Event Tracking With Typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" }) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(" "); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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