Home > Blockchain >  How to get the right type from type object with generic in typescript
How to get the right type from type object with generic in typescript

Time:05-12

I have an enum

export const trackingKeys = {
  Form: 'form',
  Video: 'video',
} as const

I have a type who give for a key a type property

export type TrackingPropertiesByKey = {
  [trackingKeys.Form]: { bar : number }
  [trackingKeys.Video]: { foo : boolean }
}

And a track function

export type TrackingEventKey =
  typeof trackingKeys[keyof typeof trackingKeys]

const track = <T extends TrackingEventKey>(
    event: TrackingEventKey,
    properties?: TrackingPropertiesByKey[T]
  ) => trackFromLib(event, properties)

Using track(trackingKeys.Form, {foo : true, bar: 1 }) doesn't give me na error.

I've got the following type :

const track: <TrackingEventKey>(event: TrackingEventKey, properties?: {
    bar: number;
} | {
    foo: boolean;
}) => void

I don't want to have properties?: {bar: number;}|{foo: boolean;} but in this case { bar : number }

CodePudding user response:

You have to also define the relation between the event parameter and T:

const track = <T extends TrackingEventKey>(
    event: T,
    properties?: TrackingPropertiesByKey[T]
) => trackFromLib(event, properties)

You specified the type event as TrackingEventKey but TypeScript needs to know that event determines the type of T to narrow down the type.

  • Related