Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 }

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading