I have the following React component that generates an HTML Table from an array of objects. The columns that should be displayed are defined through the tableColumns
property.
When looping through items
and displaying the correct columns I have to use the key
property from the tableColumn
object ({item[column.key]}
) but typescript is generating the following error:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. No index signature with a parameter of type 'string' was found on type '{}'.
What could I do to fix this? I'm lost
How I call the component:
<TableGridView
items={[
{
id: 1,
name: 'John Doe',
email: '[email protected]'
},
{
id: 2,
name: 'Lorem ipsum',
email: '[email protected]',
}
]}
tableColumns={[
{
key: 'id',
label: 'ID',
},
{
key: 'name',
label: 'Name',
}
]}
/>
My Component:
export type TableColumn = {
key: string,
label: string,
};
export type TableGridViewProps = {
items: object[],
tableColumns: TableColumn[]
};
const TableGridView: React.FC<TableGridViewProps> = ({ tableColumns, items }) => {
return (
<table>
<tbody>
{items.map(item => {
return (
<tr>
{tableColumns.map((column, index) => {
return (
<td
key={column.key}
className="lorem ipsum"
>
{item[column.key]} // error thrown here
</td>
);
})}
</tr>
);
})}
</tbody>
</table>
);
}