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

Generic object property

I have this Interface

export interface ChartDataResponseI {
  consumption: string
  generation: string
  measure_name: string
  point_delivery_number: string
  self_coverage: string
  time: string
}

What i want to achieve is to make point_delivery_number an generic object property if its possible

It should look something like this:

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 interface ChartDataResponseI<T> {
  consumption: string
  generation: string
  measure_name: string
  [T]: string
  self_coverage: string
  time: string
}

So i can pass the key like this:

ChartDataResponse<"point_delivery_number">

or

ChartDataResponse<"community_number">

>Solution :

Do you really need to have it generic? If you only have those two keys that can differ, consider something like this:

interface ChartDataResponse {
  consumption: string
  generation: string
  measure_name: string
  self_coverage: string
  time: string
}

export interface ChartDataResponsePointDelivery extends ChartDataResponse {
    point_delivery_number: number
}

export interface ChartDataResponseCommunity extends ChartDataResponse {
    community_number: number
}

Now you have a base ChartDataResponse interface, which is extended for those two different cases. It is also easy to extend it further if needed. Both ChartDataResponsePointDelivery and ChartDataResponseCommunity have all the keys of ChartDataResponse plus the additional key.

Also note that the base interface is not exported at all, so you can’t accidentally use the base interface with neither of the keys.

Often times when you are in a situation where you need to accept "any object", there is a deeper issue with how you are approaching the situation. TypeScript’s whole point is to be there to enforce and to let you know what kind of objects you are dealing with and what keys they have.

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