简体   繁体   English

Typescript 从 object 值强制 object 键

[英]Typescript force object keys from object values

I want to create a type where the object keys are the value from object values.我想创建一个类型,其中 object 键是 object 值中的值。

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.在我的示例中,我希望 xAxis 和 yAxis 作为字符串。 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.但是在“数据”属性中,xAxis 和 yAxis 的值应该用作字符串文字,这样我就可以强制用户至少有两个键和值的名称。

Right now one way it works is to define two generics and use them later.现在它的一种工作方式是定义两个 generics 并在以后使用它们。 But i hope that i can dynamically can convert the values to a type.但我希望我可以动态地将值转换为类型。

I'm using the newest typescript version.我使用的是最新的 typescript 版本。

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
    }]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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