4

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?

4
  • This answer should explains things for you: stackoverflow.com/questions/43836274/… Commented Jan 19, 2020 at 1: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. Commented Jan 19, 2020 at 1: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)" Commented Jan 19, 2020 at 14:10
  • @B.Fleming Typescript doesn't like it for the reason that doing so is literally the reason Typescript exists Commented Jan 20, 2020 at 3:29

1 Answer 1

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
}, {}));
Sign up to request clarification or add additional context in comments.

2 Comments

key return array of strings. Example: codepen.io/Luzin/pen/bGNQGGB
Sorry, maybe I wasn't clear about the issue, I will edit my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.