1

I want to set each value in an object using Typescript, but I can't seem to get it to work in any elegant way. This is what I have:

const myObject = {
    keyA: '',
    keyB: '',
};

for (const key in myObject) {
    myObject[key] = 'something';
}

But I get the typescript error:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type { keyA: string; keyB: string; }.
No index signature with a parameter of type 'string' was found on type { keyA: string; keyB: string; }. TS7053

Shouldn't Typescript know that key must be a key of myObject?

Spliid
  • 478
  • 1
  • 4
  • 12
  • 1
    See here: https://stackoverflow.com/a/56833507/3233827 – ssc-hrep3 Dec 17 '19 at 14:28
  • @ssc-hrep3 but then I lose the beauty of Typescript. My object has a specific set of keys, and if I set that type, I don't get type checking for my keys – Spliid Dec 17 '19 at 14:30
  • @nickzoum It does remove the error, but then I don't get type checking for the keys in the object anymore. My object has a specific set of keys, and I want Typescript to enforce them – Spliid Dec 17 '19 at 14:34
  • 2
    Add this to your code, run as javascript, to see potential issues: `Object.prototype.trolled = 123;` – ASDFGerte Dec 17 '19 at 14:34
  • @ASDFGerte has pointed out the issue: Typescript only knows what it can know (and has to assume the worst) *statically, at compile time*. Iteration happens at *runtime*. – Jared Smith Dec 17 '19 at 14:36
  • @nickzoum that does seems to work, but then I have to type in all the fields twice, which is what I wanted to avoid – Spliid Dec 17 '19 at 14:37
  • Btw, other related material is e.g. https://github.com/Microsoft/TypeScript/issues/12870 – ASDFGerte Dec 17 '19 at 14:40
  • @JaredSmith It does seem to be able to in other cases, such as when doing if (keyA in myObject) then myObject.keyA – Spliid Dec 17 '19 at 14:42
  • @Spliid that's because you can verify a literal statically, which you can't do with random string assignment. – Jared Smith Dec 17 '19 at 16:23
  • Not helpful whoever closed this issue. How do you set type properly in the loop?? – Nic Scozzaro Feb 10 '20 at 23:11

0 Answers0