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

Inferring the type from the object passed to a component

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

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

>Solution :

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

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