newbie
newbie

Reputation: 600

TypeScript Type Error - Element implicitly has an 'any' type because expression of type 'string' can't be used to index type

I am getting type errors in my code. I am not sure what I am missing. I have tried a number of things but didn't get anything fruitful.

Can anyone please help me with this to fix the type errors?

Thanks in advance

The code looks like:

interface Res {
    "a": {"x": number, "y": number},
    "b": {"x": number, "y": number},
    "c": {"x": number, "y": number}
}

interface Obj {
    "a": number,
    "b": number,
    "c": number
}

const rule: Obj = {
    "a": 10,
    "b": 10,
    "c": 20
}

const obj: Obj = {
    "a": 100,
    "b": 150,
    "c": 500
}

const foo = () => {
  const res: Partial<Res> = {};
  for (const key in obj) {
      res[key] = {
        x: Math.floor(obj[key] / rule[key]),
        y: obj[key] % rule[key]
      };
  }
  return res;
}

console.log(foo());

Error: (As you can see the red lines in the image give the error but the code runs fine)

enter image description here

Upvotes: 1

Views: 1909

Answers (1)

kaosdev
kaosdev

Reputation: 309

Using the for in, the key variable get a typing of string. You can't use a string to access an object with a set of defined properties ("a", "b", "c").

To resolve this you could either change Res and Obj interfaces to accept an index signature:

interface Res {
    [key: string]: {x: number ...}
}

Or you could cast the value of key to be in the set of properties that Res accept. res[key as keyof Res] = ...

Upvotes: 5

Related Questions