Home > Net >  Inferring the type from the object passed to a component
Inferring the type from the object passed to a component

Time:11-03

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>
  );
}

Example codesandbox

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>
  );
};

codesandbox

  • Related