Home > Net >  Generic object property
Generic object property

Time:06-10

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:

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">

CodePudding user response:

You can use a simple intersection.

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

type ChartDataWithProp<T> = ChartDataResponseI & T;

const chartData: ChartDataWithProp<{point_delivery_number: number, round: string}> = {
  consumption: 'string',
  generation: 'string',
  measure_name: 'string',
  self_coverage: 'string',
  time: 'string',  
  point_delivery_number: 2,
  round: 'yes'
};

TSPlayground

CodePudding user response:

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.

CodePudding user response:

use inheritance

interface ChartDataResponseI {
  consumption: string
  generation: string
  measure_name: string
  //point_delivery_number: string <- if its not default remove it
  self_coverage: string
  time: string
}

interface another extends ChartDataResponseI {
  point_delivery_number: string
  //or
  anything: string
}
  • Related