Closed
Description
TypeScript Version: 3.8.3
Search Terms:
"Type 'string' cannot be used to index type"
"Type 'string' cannot be used to index type clone"
Code
type Obj = { [index: string]: any }
function f<T extends Obj>(original: T) {
const o1 = { ...original }
const o2 = {} as Obj
Object.keys(o1).forEach(k => {
// Error: Type 'string' cannot be used to index type 'T'.
o1[k] = 1 // this should be ok
o2[k] = 1 // why would this be ok if the above is not?
const a = o1[k] // and this is fine?
})
}
Expected behavior:
The error should not exist as:
(1) o1 has the keys as in T.
(2) T extends Obj. So even if (1) was not true, it should be ok.
It's does not seem right that the next two assignments are ok if o1[k] = 1 is not.
If this is intended behavior, like the one in #32704, I just can't make sense of it. Specially considering the similar assignments that do not raise errors.
Actual behavior:
o1[k] = 1 yelds "Type 'string' cannot be used to index type 'T'."