Skip to content

for .. in type is wrong for objects as const #49621

Closed as not planned
Closed as not planned
@fabio-colella-md

Description

@fabio-colella-md

Bug Report

When declaring a new object as const, if we then use a for .. in structure, the type of the key is just inferred as string and not as the more restricted type that const defines. This causes issues especially when trying to use that key to get the corresponding property.

🔎 Search Terms

is:issue for in as const

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about const

⏯ Playground Link

https://www.typescriptlang.org/play?ts=4.8.0-dev.20220621#code/MYewdgzgLgBAtgTwMLmgeQEYCsYF4YDeAsAFAwwCGAXDAERQCm0AjLQDSnkY31NQBMtUgF9KEGKEhQA3KVIAzEACcYACknQYIbAGkGCGAEsw8ZKiiYsASkKdTKKZYDa2rHoQBdEaSA

💻 Code

const myConstObj = {
  a: "test1",
  b: "test2"
} as const;

for (const objKey in myConstObj) {
  myConstObj[objKey]
}/* ^^^^^^^^^^^^^^^^
    const objKey: string
    --------------------
    Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 
    '{ readonly a: "test1"; readonly b: "test2"; }'.
        No index signature with a parameter of type 'string' was found on type 
    '{ readonly a: "test1"; readonly b: "test2"; }'.(7053)
*/

🙁 Actual behavior

When using the key to get the prop, we are told that the prop would have type any because the key is of type string.
Screenshot 2022-06-21 at 16 16 46

🙂 Expected behavior

No error should be reported, as the correct inferred type for the key should be the union of the keys (i.e. 'a' | 'b' in this case) of the const object.

🤔 Workaround

"Coerce" the key type to be what we would have expected, so in this case:

const myConstObj = {
  a: "test1",
  b: "test2"
} as const;

for (const _objKey in myConstObj) {
  const objKey = _objKey as keyof typeof myConstObj
  myConstObj[objKey]
}

Screenshot 2022-06-21 at 16 17 35

Metadata

Metadata

Assignees

No one assigned

    Labels

    DeclinedThe issue was declined as something which matches the TypeScript visionSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions