Indexable type – TypeScript

Below syntax,

interface StringArray {
    [index: number]: string;

states that when a StringArray is indexed with a number, it will return a string. For example –

let myArray: StringArray;
myArray = ["Bob", "Fred"];
let myStr: string = myArray[0];

So, myArray is type constrained on values stored as string type, by declaring it with type StringArray. Key(index) is always string type, under the hood(JavaScript), despite mentioning it as number

From the below syntax,

class Animal{
  name: string;

class Dog extends Animal{
  breed: string;

interface NotOkay {
  [x: number]: Animal;
  [x: string]: Dog;   
  1. What does NotOkay syntax state?

From the below syntax,

interface NumberDictionary {
    [index: string]: number;
    length: number;    // ok, length is a number
    name: string;      // error, the type of 'name' is not a subtype of the indexer
  1. What does NumberDictionary state?

  1. Why these two syntax are wrong? error TS2413 & error: TS2411

14 thoughts on “Indexable type – TypeScript”

  1. Undeniably believe that which you stated. Your favorite reason appeared to be on the web the simplest thing to be aware
    of. I say to you, I definitely get annoyed while people think about worries that
    they just don’t know about. You managed to hit the nail upon the
    top and also defined out the whole thing without having side effect , people could take a signal.
    Will probably be back to get more. Thanks


Leave a Comment