HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptreactCritical

'string' can't be used to index type '{}'

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
indexusedcanstringtype

Problem

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:



My Component:

export type TableColumn = {
  key: string,
  label: string,
};

export type TableGridViewProps = {
  items: object[],
  tableColumns: TableColumn[]
};

const TableGridView: React.FC = ({ tableColumns, items }) => {
  return (
    
      
        {items.map(item => {
          return (
            
              {tableColumns.map((column, index) => {
                return (
                  
                    {item[column.key]} // error thrown here
                  
                );
              })}
            
          );
        })}
      
    
  );
}

Solution

items: object[],


While technically it is a JavaScript object, the type can be better. For Typescript to correctly help you identify mistakes when accessing objects properties, you need to tell it the exact shape of the object. If you type it as object, typescript cannot help you with that. Instead you could tell it the exact properties and datatypes the object has:

let assistance: { safe: string } = { safe: 1 /* typescript can now tell this is wrong */ };
  assistance.unknown; // typescript can tell this wont really work too


Now in the case that the object can contain any sort of key / value pair, you can at least tell typescript what type the values (and the keys) have, by using an object index type:

items: {
   [key: string]: number | string,
  }[]


That would be the accurate type in the case given.

Code Snippets

items: object[],
let assistance: { safe: string } = { safe: 1 /* typescript can now tell this is wrong */ };
  assistance.unknown; // typescript can tell this wont really work too
items: {
   [key: string]: number | string,
  }[]

Context

Stack Overflow Q#57350092, score: 153

Revisions (0)

No revisions yet.