I am learning Typescript by reading this official document about indexer type.
I can't understand this code:
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
}
let myDict : NumberDictionary;
myDict[10] = 23;
name: string;// error, the type of 'name' is not a subtype of the indexer
I don't understand the comment on this line. Why name must be subtype of the indexer?
Because for any string
access TypeScript will assume type number
(based on [index: string]: number;
). So if name: string;
was allowed the following would assume number
but really you might think string:
let x: NamedDictionary = Object.create(null);
let n = "name";
let y = x[n]; // TypeScript assumes `number`
let z = x["name"]; // Would you want `string`?
See the inconsistency between y
and z
^