Advertisement
Advanced TypeScript, Index Signatures & Record Types

Why can't you have both a string index signature and a NUMBER index signature with incompatible value types on the same interface?

Short answer

JavaScript actually coerces numeric keys to strings under the hood (obj[1] and obj['1'] access the same property), so TypeScript requires that a number index signature's value type be assignable to the string index signature's value type when both exist together, ensuring…

Save TypeScript mock interview
Advertisement
AModel answer
JavaScript actually coerces numeric keys to strings under the hood (obj[1] and obj['1'] access the same property), so TypeScript requires that a number index signature's value type be assignable to the string index signature's value type when both exist together, ensuring consistency for keys that could be accessed either way.
interface Bad {
  [index: string]: string;
  // [index: number]: number; // Error: numeric index type not assignable to string index type
}
interface Good {
  [index: string]: string | number;
  [index: number]: number; // OK: number is assignable to (string | number)
}
Real-world example
Understanding a specific and somewhat obscure compiler error when trying to type an array-like object with mixed access patterns.
Likely follow-ups
  • In practice, when would a class or object realistically need both index signature types together?
Related topics