简体   繁体   中英

Typescript force object keys from object values

I want to create a type where the object keys are the value from object values.

Example:

type AreaChartData = {
  xAxis: string;
  yAxis: string;
  data: {
    [Key in AreaChartData['xAxis'] | AreaChartData['yAxis']]: string | number;
  }[];
};

In my example i want xAxis and yAxis as strings. But in the "data" attribute the values from xAxis and yAxis should be used as string literals so that i can force the user to have at least two keys with the names of the values.

Right now one way it works is to define two generics and use them later. But i hope that i can dynamically can convert the values to a type.

I'm using the newest typescript version.

You will never be able to convert a value to a type.

Types only exists at compile time.

Value only exists at run time.

The type you created in this question is equivalent to:

type AreaChartData = {
  xAxis: string;
  yAxis: string;
  data: {
    [ key:string]: string | number;
  }[];
};

Here is a proposal:

type AreaChartData2<xAxis extends string='x',yAxis extends string ='y'> = {
  xAxis: xAxis;
  yAxis: yAxis;
  data: {
    [key in xAxis|yAxis]: string | number;
  }[];
};

const a : AreaChartData2 <'lat','long'> = {
    xAxis:'lat',
    yAxis:'long',
    data:[{
        lat:"plouf",
        long:23
    }]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM