Curious if there might be a bug in TypeScript? Just seeking clarification on whether my code is incorrect or if there is an actual issue with the language.
interface Something {
key1: string;
key2: number;
key3: boolean;
}
const someObject: Something = {
key1: '123',
key2: 123,
key3: false
}
for (const key in someObject) {
console.log(someObject[key]); // TS error
}
Note: Not looking for workarounds as this code works fine for me. Simply trying to determine if I am making an error or if TypeScript has a potential bug.
for (const [key, value] of Object.entries(someObject)) {
console.log(key, value);
}
or
for (const key in values) {
console.log(key, values[key as keyof DirectDepositDTO]);
}
I understand that the type of key
may be string
, but shouldn't it ideally be keyof Something
?
P.S. The question is marked as a duplicate, however, I am not in need of a solution right now as I already have one. What I seek to clarify is if there might be a bug in TypeScript. Using for (const key in someObject) {
should automatically mean that key
will represent keyof Something
. There should be no requirement to redefine the types.