Skip to content

Cloned object with extended generic type cannot have values assigned to its existing keys #37604

Closed
@cantiero

Description

@cantiero

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'."

Playground Link:
https://www.typescriptlang.org/play/index.html#code/C4TwDgpgBA8gRgKygXigbygbQJYDsAmEAHgFxQDOwATngOYC6ZAhriFAL4BQAZgK64BjYNgD2uKNwA8AFSjFgEAuViIAfAAoRNWniYAbMtICU6KJyhQBYylBEBGFKYB0Lrdh259Hc5evBbAEyOaOxQTMrwCD6REEJOANYQIOSadkZO3FoAokwCABbq8Siq6D4W9pjx9I4OAPS1UMB52MrkeSK8evhQcNAi8WWBldWodQ0A7nls4x1djc3KvbZF2Nzz0ExwIgBu0C1QuCLAAPw+7Eac7EA

Related Issues:
#31661, #32704

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions