Skip to content

    ↑↓ move · ⏎ open · esc close

    TS2536

    Cannot be used to index

    Type 'K' cannot be used to index type 'T'.

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

    You indexed a type parameter with another type parameter, and the compiler has no reason to believe the key exists.

    Reproduction

    type Get<T, K> = T[K]

    The build asserts this emits exactly this code.

    Why the compiler says this

    Inside a generic, `T` is not an object yet — it is a promise that one will arrive. `K` is not a key of it, just another unknown. Asking for `T[K]` is asking the compiler to guarantee something about two things it has never seen. The fix is not a cast: it is telling it how the two relate.

    Fixes

    1. 01
      type Get<T, K extends keyof T> = T[K]
      
      type Name = Get<{ name: string }, 'name'>

      Constrain `K` to `keyof T`. Now the relationship is written down, and the compiler can check every call site instead of trusting one.

    2. 02
      type Get<T, K> = K extends keyof T ? T[K] : never
      
      type Missing = Get<{ name: string }, 'nope'>

      Or ask at use time instead of at the door. This accepts any `K` and answers `never` for keys that are not there — the right shape when a missing key is a normal answer rather than a mistake.

    Takeaway

    Constraints are how two type parameters are introduced to each other. Without one they are strangers, and the compiler will not vouch for either.

    Where to go next

    Errors