1

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

1 Answer 1

5

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] = ...

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for the explanation and solutions. Works perfectly!

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.