mxmtsk
mxmtsk

Reputation: 4685

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

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>
  );
}

Upvotes: 174

Views: 249292

Answers (7)

Jamie Marshall
Jamie Marshall

Reputation: 2306

Simplest answer taken from here

const map: { [key: string]: any } = {};
map['foo'] = 'foo'; // No problem!

You can replace any with whatever type suits you or not. In js we often uses objects as collections and not as objects. It's completely fine not to define a type for objects and use them as so. Requiring a type definition for every object in js is just insanity.

Upvotes: 3

Bar Horing
Bar Horing

Reputation: 5975

function isKeyInObject<T extends Object>(
  obj: T,
  key: string | number | symbol,
): key is keyof T {
  return obj[key as keyof typeof obj] !== undefined;
}

const obj = {
  'key1': 'A',
  '2': 'B',
  3: 'C'
}

const bar = (key: string | number | symbol) => {
  if (isKeyInObject(obj, key)) {
    const value = obj[key] 
    console.log('value=', value)
    return;
  }
    console.log(`${String(key)} not in obj`)
}

bar('7')
bar(3)

Typescript Playground

Upvotes: 0

Chan Jing Hong
Chan Jing Hong

Reputation: 2471

First of all, defining the type of items as an array of objects is a bad idea, as it defeats the purpose of Typescript. Instead define what type of objects the array will contain. I would do it this way:

type Item = {
  id: number,
  name: string,
  email: string,
}

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

After that if you're absolutely sure that the key would exist in item, you can do the following to tell Typescript that you are accessing a valid index.

<td
  key={column.key}
  className="lorem ipsum"
>
  {item[column.key as keyof typeof Item]}
</td>

Upvotes: 44

Jonas Wilms
Jonas Wilms

Reputation: 138557

  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.

Upvotes: 152

notacorn
notacorn

Reputation: 4119

If it's a pedantic javascript object that doesn't make sense to create type definitions per field for, and doesn't make sense as a class definition, you can type the object with any and typescript will let you index however you want.

ex.

//obviously no one with two brain cells is going to type each field individually
let complicatedObject: any = {
    attr1: 0,
    attr2: 0,
    ...
    attr999: 0
}

Object.keys(complicatedObject).forEach(key => {
    complicatedObject[key] += 1;
}

Upvotes: 29

Baraka Ally
Baraka Ally

Reputation: 19

try adding type any[]

items:any[]

Upvotes: -31

Alex Mckay
Alex Mckay

Reputation: 3706

Use Generics

// bad
const _getKeyValue = (key: string) => (obj: object) => obj[key];

// better
const _getKeyValue_ = (key: string) => (obj: Record<string, any>) => obj[key];

// best
const getKeyValue = <T extends object, U extends keyof T>(key: U) => (obj: T) =>
      obj[key];

Bad - the reason for the error is the object type is just an empty object by default. Therefore it isn't possible to use a string type to index {}.

Better - the reason the error disappears is because now we are telling the compiler the obj argument will be a collection of string/value (string/any) pairs. However, we are using the any type, so we can do better.

Best - T extends empty object. U extends the keys of T. Therefore U will always exist on T, therefore it can be used as a look up value.

Here is a full example:

I have switched the order of the generics (U extends keyof T now comes before T extends object) to highlight that order of generics is not important and you should select an order that makes the most sense for your function.

const getKeyValue = <U extends keyof T, T extends object>(key: U) => (obj: T) =>
  obj[key];

interface User {
  name: string;
  age: number;
}

const user: User = {
  name: "John Smith",
  age: 20
};

const getUserName = getKeyValue<keyof User, User>("name")(user);

// => 'John Smith'

Upvotes: 20

Related Questions