Currently, I am diving into Typescript with the help of this informative guide on indexer types.
There is a specific piece of code that has me puzzled:
interface NumberDictionary {
[index: string]: number;
length: number; // okay, length should be a number
name: string; // error, 'name' type is not compatible with indexer
}
To start, why include 'length' in the index type?
let myDict : NumberDictionary;
myDict[10] = 23;
I'm confused about why there is a "length" property in the NumberDictionary when it's supposed to have an index like a[10]. Is an index type essentially an array, considering JavaScript arrays have lengths? If so, why define a length property in this example? Is it necessary? Apologies for my confusion – you can tell I'm trying to wrap my head around it.
Secondly,
name: string;// error, the type of 'name' is not a subtype of the indexer
The comment here has me scratching my head. Why does 'name' need to be a subtype of the indexer? Isn't an indexer something like a[10] = "Tom"? So, what exactly is a subtype of the indexer in this scenario?