I want to pass any random list of objects at least containing and id property to my generic component. How can I force displayValue prop to be a string with a name of one of the properties of options object?
export default function App() {
const options = [
{ id: 1, name: "Apple" },
{
id: 2,
name: "Banana"
},
];
return (
<div className="App">
<ListDisplay options={options} displayValue="name" />
</div>
);
}
CodePudding user response:
If we change your ListDisplay component to be generic, we can use keyof T
:
interface Id {
id: number | string;
}
interface ListDisplayProps<T extends Id> {
options: T[];
displayValue: keyof T;
}
export const ListDisplay = <T extends Id>(props: ListDisplayProps<T>) => {
const { options, displayValue } = props;
return (
<ul>
{options.map((option) => (
<li key={option.id}>{option[displayValue]}</li>
))}
</ul>
);
};