1

I have the following Typescript code.

type myType = {
  a: number,
  b?: number,
};

const c:myType = {a: 1, b:2};
const d:myType = {a: 3};
Object.entries(c)
    .forEach(([key, value]) => {
        console.log(d[key])
      }
    )
})

It works as expected. It prints out 3\n4\n. However, when I run tsc on this code (the typescript to javascript compiler) with the --strict flag, it complains about this line:

myFile.ts:777:19 - error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'myType'.
  No index signature with a parameter of type 'string' was found on type 'myType'.

777       console.log(d[key]);
                  ~~~~~~

Why can't I use string key to index myType? And how can I eliminate this error? Again, the code actually runs properly.

Saqib Ali
  • 11,931
  • 41
  • 133
  • 272
  • 1
    Yes, compiling with tsc with the --strict flag. My CI uses that as a code-quality checker. – Saqib Ali Apr 07 '23 at 00:39
  • Please see the answers to the linked questions. You're only allowed to index into objects with known keys. `Object.entries(obj)` returns tuples whose first elements are of type `string` and not `keyof typeof obj` type because excess properties are possible; if you want to *assert* that `key` is of type `keyof typeof obj` and then index, you can do so. – jcalz Apr 07 '23 at 00:44
  • What is `keyof typeof obj`? I read the linked question and your comment, but its not clear to me. Perhaps show a code-fragment that directly solves my particular problem. – Saqib Ali Apr 07 '23 at 04:04
  • Using the `Entries` definition in [this answer to the top-linked question](https://stackoverflow.com/a/62055863/2887218) gives you [this approach](https://tsplay.dev/WG88vw). I hope that is more clear now. – jcalz Apr 07 '23 at 14:18

0 Answers0