typescript type_error ai_generated true

TS2536: Type 'K' cannot be used to index type 'T'

ID: typescript/ts-mapped-type-error

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
5 active

Root Cause

The key type is not compatible with the object's index signature. Constrain the key to keyof T or add proper index signatures.

generic

Workarounds

  1. 90% success Constrain the key type to keyof T
    function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
      return obj[key];
    }

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

  2. 85% success Use Record type for objects with dynamic keys
    const map: Record<string, number> = {};
    // Or use Map for truly dynamic keys:
    const map = new Map<string, number>();

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

Dead Ends

Common approaches that don't work:

  1. Add [key: string]: any index signature to the type 70% fail

    Makes all property access return any, eliminating type safety for known properties

Error Chain

Leads to:
Preceded by:
Frequently confused with: