Home > Software engineering >  Typescript generics for 2nd optional argument
Typescript generics for 2nd optional argument

Time:01-11

Generics in typescript is pretty advanced for me. But I managed to got this working

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') //            
  • Related