TS7053: Element implicitly has an 'any' type because expression can't be used to index type
You're indexing an object with a string/variable key whose exact literal value TypeScript can't verify matches one of the object type's known keys — commonly `obj[someVariable]` where `someVariable` is typed as plain `string`. Either add an index signature to the object's type, or narrow the key to a specific union of literal keys (`keyof typeof obj`).
What causes this error
Under `noImplicitAny` (on by default in strict mode), indexing an object with a key typed as general `string` is flagged because TypeScript can't prove that key actually exists on the object at compile time — the lookup would silently be `any` otherwise, defeating the point of typing the object in the first place.
The Fix
const colors = { red: '#f00', green: '#0f0', blue: '#00f' };
function getColor(key: string) {
return colors[key]; // TS7053 — key is just `string`, not a known literal key
}
// Fix 1 — narrow the parameter to the actual set of valid keys
function getColor(key: keyof typeof colors) {
return colors[key]; // now type-safe
}
// Fix 2 — if truly dynamic keys are expected, add an index signature
const colors: Record<string, string> = { red: '#f00', green: '#0f0', blue: '#00f' };Common causes / variations
- Indexing a config/lookup object with a variable typed as plain `string` instead of a union of its actual keys
- Iterating `Object.keys(obj)` (which TypeScript types as `string[]`) and using each key to index `obj` again
- Building a dynamic form/field-mapping object without declaring an index signature up front
Related errors
See also: TS2532 Object is possibly undefined, TS2345 Argument not assignable.
Comments
Loading comments...