TypeScript Reference ยท Error Codes Worth Knowing
TypeScript error TS7053: Element implicitly has an any type
Reference for TypeScript error TS7053: why indexing an object with a string or number key fails, and how keyof, index signatures, Record and Map fix it.
TS7053 is reported when you index into a value with obj[key] and the compiler cannot prove that key is a valid key of that type. The message is Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ a: number; }', and it is only an error under noImplicitAny.
A string is a much bigger set than the few property names an object type declares. TypeScript will not guess that your string happens to be one of them. You either narrow the key to the real property names, or describe the object as a dictionary.
const prices = { apple: 1, pear: 2 }; const key: string = "apple"; prices[key]; // TS7053
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
| Fix | Result type | Best for |
|---|---|---|
Type the key as keyof typeof obj |
The exact property type | Keys known at compile time. |
Index signature { [key: string]: T } or Record<string, T> |
T (or T | undefined with noUncheckedIndexedAccess) |
True dictionaries. |
A type guard such as key in obj wrapped in a predicate |
Narrowed key | Keys from user input, narrowed once. |
Map<string, T> |
T | undefined from get |
Dynamic key sets with frequent changes. |
Object.entries / Object.keys iteration |
[string, T][] or string[] |
Looping; note keys returns string[], not keyof. |
Edge cases: an enum or a union of literals as the key type works directly. Indexing an array with a string fails the same way; use a number.
Usage notes
Object.keys(obj)returnsstring[], soobj[k]inside the loop triggers this error. UseObject.entries(obj)or cast the key array once with a clear comment.- Why
inalone does not narrowstring: theinoperator narrows unions, not plain strings, which is why the guard function returns a type predicate. - Use
as constfor lookup tables whose keys should become a union of literals. noUncheckedIndexedAccessmakes dictionary readsT | undefined, which is honest: the key may be missing.- Do not cast the object to
any((obj as any)[key]); aRecordtype costs one line and keeps the checking. - Prototype keys. A plain object also has
toString,constructorand so on; useObject.hasOwn(obj, key)or aMapfor untrusted keys.