-
Notifications
You must be signed in to change notification settings - Fork 13.1k
Closed as not planned
Labels
DeclinedThe issue was declined as something which matches the TypeScript visionThe issue was declined as something which matches the TypeScript visionSuggestionAn idea for TypeScriptAn idea for TypeScript
Description
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
💻 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.

🙂 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]
}Metadata
Metadata
Assignees
Labels
DeclinedThe issue was declined as something which matches the TypeScript visionThe issue was declined as something which matches the TypeScript visionSuggestionAn idea for TypeScriptAn idea for TypeScript
