Next.js Discord

Discord Forum

Error when trying to set a key when looping over an array

Unanswered
Giant Chinchilla posted this in #help-forum
Open in Discord
Giant ChinchillaOP
My code:
interface Props {
  items: {
    id: Number;
    name: String;
    price: Number;
  }[];
}

const Results = ({ items }: Props) => {
  console.log(items);
  if (items.length === 0) {
    return <span>Žádné díly nenalezeny</span>;
  }

  return items.map((item) => <div key={item.id}>{item.name}</div>);
};

export default Results;

Getting an typescript error:
Type 'Number' is not assignable to type 'Key | null | undefined'

Where is the issue ?

4 Replies

try making the number a string for the key (ie item.id.toSTring())
Shy Albatross
return items.map((item) => <div key={`item-${item.id}`}>{item.name}</div>);
@riský try making the number a string for the key (ie `item.id.toSTring()`)
Giant ChinchillaOP
This works, but when i tried passing a string as a key, the same error appeared, im a bit confused about why
Type 'String' is not assignable to type 'Key | null | undefined'