typescript type_error ai_generated true

error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type

ID: typescript/ts2339-index-signature

Also available as: JSON · Markdown
92%Fix Rate
92%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
5 active

Root Cause

Dynamic property access on a typed object. TypeScript can't verify the key exists.

generic

Workarounds

  1. 92% success Add index signature: { [key: string]: ValueType }
    interface MyObj { [key: string]: string | number; }

    Sources: https://www.typescriptlang.org/docs/handbook/2/objects.html#index-signatures

  2. 90% success Use Record<string, T> type for key-value objects
    const obj: Record<string, number> = {};

    Sources: https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type

  3. 85% success Use keyof typeof obj to restrict keys to known ones
    Use keyof typeof obj to restrict keys to known ones

    Sources: https://www.typescriptlang.org/docs/handbook/2/keyof-types.html

Dead Ends

Common approaches that don't work:

  1. Cast to any: (obj as any)[key] 70% fail

    Loses all type safety for the access

Error Chain

Preceded by:
Frequently confused with: