3

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?

Andrey Luzin
  • 31
  • 1
  • 4
  • This answer should explains things for you: https://stackoverflow.com/questions/43836274/type-undefined-cannot-be-used-as-index-type – Koronag Jan 19 '20 at 01:44
  • I'm not familiar with TypeScript, but JavaScript implicitly coerces the array in `key` into a string when `key` is used as an object property. TypeScript probably doesn't like this for whatever reason. You can likely resolve this problem by explicitly doing `key = key.toString();` to stop TypeScript from complaining. – B. Fleming Jan 19 '20 at 01:58
  • @Koronag, I tried use non null assertion operator (`i => i.object_id!`). This led to an error "Type 'string[]' cannot be used as an index type.ts(2538)" – Andrey Luzin Jan 19 '20 at 14:10
  • @B.Fleming Typescript doesn't like it for the reason that doing so is literally the reason Typescript exists – millimoose Jan 20 '20 at 03:29

1 Answers1

1

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
}, {}));
KingDarBoja
  • 1,033
  • 6
  • 12