Skip to content
TS7015

    ↑↓ move · ⏎ open · esc close

    TS7015

    Array indexed with a non-number

    Element implicitly has an 'any' type because index expression is not of type 'number'.

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

    Arrays describe numeric positions; a string key such as `first` is not one of those positions.

    Reproduction

    const values = [1, 2]
    
    values['first']

    The build asserts this emits exactly this code.

    Why the compiler says this

    JavaScript objects can carry arbitrary properties, but an array type only promises its numbered elements and standard members. TypeScript will not invent a string index signature and silently turn the result into `any`.

    Fixes

    1. 01
      const values = [1, 2]
      
      const first = values[0]

      Use a numeric position when the collection is ordered.

    2. 02
      const values: Record<string, number> = {
        first: 1,
        second: 2,
      }
      
      const first = values['first']

      Use a keyed object or `Record` when names, rather than positions, identify values.

    Takeaway

    Choose the data structure that matches the lookup: arrays for positions, records for names.

    Where to go next

    Errors