TypeScript error of using variable as key of object - React

Viewed 37

I have a problem with the type of variable key in TypeScript. The component is receiving an array of an object (dataToShow) from a parent. The function is taking the keys and putting this into an arrayOfKeys. I'm trying to map thru data to show and create divs according to that. Unfortunately I'm getting an error: Element implicitly has an 'any' type because expression of type 'keyof Data' can't be used to index type '{ id: number; brand?: string | undefined; hostname?: string | undefined; description?: string | undefined; contractNumber?: string | undefined; model?: string | undefined; user?: string | undefined; }'. No index signature with a parameter of type 'number' was found on type '{ id: number; brand?: string | undefined; hostname?: string | undefined; description?: string | undefined; contractNumber?: string | undefined; model?: string | undefined; user?: string | undefined; }'.ts(7053)

The component:

type Data = {
  id: number;
  brand?: string;
  hostname?: string;
  description?: string;
  contractNumber?: string;
  model?: string;
  user?: string;
}[];

const Module: React.FC<{ dataToShow: Data }> = ({ dataToShow }) => {

  const arrayOfKeys: string[] = [];

  for (let data of dataToShow) {
    for (let name in data) {
      arrayOfKeys.push(name);
    }
    break;
  }

  return (
    <div>
      {dataToShow.map((x) => {
        return <div>
          {x[arrayOfKeys[0] as keyof Data]}
          </div>;
      })}
    </div>
  );
};

export default Module;
1 Answers

Data is an array, so keyof Data would actually give you things like concat, splice, etc.

It should be Data[number] (or any number, actually, even Data[123.456] works):

{x[arrayOfKeys[0] as keyof Data[number]]}
Related