Skip to content

    ↑↓ move · ⏎ open · esc close

    TS7053

    Implicit any from a string index

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

    The compiler’s own words. Not translated — this is the string you pasted into a search box.

    You indexed an object with a plain `string`, and the compiler cannot tell which property you meant — so the result would be `any`, and `strict` will not allow that quietly.

    Reproduction

    declare const obj: { a: number }
    declare const key: string
    
    const value = obj[key]

    The build asserts this emits exactly this code.

    Why the compiler says this

    `string` is every string, and `obj` has exactly one key. The compiler cannot rule out `obj["nonsense"]`, which has no type at all, so the honest result is `any` — and under `noImplicitAny` an `any` you did not ask for is an error rather than a silent hole. The message is describing a gap in what it knows, not a mistake in what you wrote.

    Fixes

    1. 01
      declare const obj: { a: number }
      declare const key: keyof typeof obj
      
      const value = obj[key]

      Narrow the key to the keys that exist. `keyof typeof obj` is `"a"`, and indexing by it is exact.

    2. 02
      declare const obj: Record<string, number>
      declare const key: string
      
      const value = obj[key]

      Or say the object really does accept any string. An index signature is a promise about every key, and it is the right answer when the object is a dictionary rather than a fixed shape.

    Takeaway

    Decide which one the object is: a fixed shape you index by its own keys, or a dictionary that accepts any. Most of these errors are an object being used as both.

    Where to go next

    Errors