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.