Andrey Luzin
Andrey Luzin

Reputation: 41

Type 'string[]' cannot be used as an index type.ts(2538)

TS Error:

Type '(string | undefined)[]' cannot be used as an index type.ts(2538)

Code:

Object.values(payload.reduce((acc, obj) => {
  let key = obj.values.map(i => i.object_id);
  if (!acc[key]) {
    acc[key] = []
  }  
  acc[key].push(obj)
  return acc
}, {}))

Works fine in the javascript code. Why?

Upvotes: 4

Views: 9075

Answers (1)

KingDarBoja
KingDarBoja

Reputation: 1053

Looks like you are trying to access an array value by using an array key as this line:

let key = obj.values.map(i => i.object_id);

Returns an array of strings and assign it to the key variable.

EDIT What I mean is that you can't use an array as index. Try to assign a string value to key instead of the mapping result.

Something like this:

Object.values(list.reduce((acc,obj) => {
  let keys = obj["values"].map(i => String(i.object_id));
  console.log(`Result mapping key`);
  console.log(keys);

  for (const subkey in keys) {
    if (!acc[subkey]) {
      acc[subkey] = []
    }
    acc[subkey].push(obj);
  }
  return acc
}, {}));

Upvotes: 1

Related Questions