1

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.

1
  • You need a generic type parameter here Commented Jan 24, 2023 at 21:38

1 Answer 1

1

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
    }]
}
Sign up to request clarification or add additional context in comments.

1 Comment

I would replace {[key in xAxis|yAxis]: string | number;} by Record<xAxis|yAxis, string | number>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.