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

Type for a property of an object in an array of objects

I have a select React component that receives 2 props: options which is an array and a callback function that receives a selected object

<Select options={options} onSelect={onSelect} />

where

const options = [
  { name: 'foo', values: ['foo', 'bar'] },
  { name: 'bar', values: ['baz', 'etc...'] },
  ...
];

const onSelect = (selected: Selected) => { /*implementation*/ }

Where Selected is

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

{
  search: string;
  [name property from first object in the array]: some of the values of the same object;
  [name property from second object in the array]: some of the values of the same object;
  ...
}

How can I type Selected properly to reflect only the values in the name properties in the array?

>Solution :

The key is of type string and the values are the specific values from each object in the options array, using the array index as the type. This will ensure that only the properties from the options array are allowed in Selected.

type Selected = {
  search: string,
  [key: string]: (options[number]['values'][number]);
}

what about key, is there a way to limit it to what’s in the array?

Yes, you can use a type assertion to limit the key to only the names of the properties in the options array:

type Selected = {
  search: string,
  [key in keyof typeof options[number]['name']]: typeof options[number]['values'][number];
}
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