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