Learning about generics in typescript has been quite challenging for me. However, I was able to make it work successfully.
export type Events = {
LOGIN: undefined
NAVIGATION: {
screen: string
}
SUPPORT: {
communication_method: 'chat' | 'email' | 'phone'
}
}
export function trackEvent<K extends keyof Events>(eventName: K, eventValues: Events[K]) {
if (Platform.OS === 'web') return
logEvent(eventName, eventValues ?? {})
}
trackEvent('LOGIN', undefined) // no TS error
// is there a way to make this work with just trackEvent('LOGIN')
trackEvent('SUPPORT') // 👍 TS error because missing 2nd argument
trackEvent('SUPPORT', { communication_method: 'chat' }) // TS helps writing this
However, I am wondering if there is a method to have trackEvent('LOGIN')
work without any errors and trackEvent('SUPPORT')
trigger an error?