1

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 Answer 1

1

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]]}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.