Nicolas S.Xu Nicolas S.Xu - 2 months ago 23
TypeScript Question

typescript "not a subtype of the indexer", what does it mean?

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
}


First, why do you put 'length' inside index type???

let myDict : NumberDictionary;
myDict[10] = 23;


NumberDictionary is an index type. Why there is a length in the NumberDictionary definition? Index type is supposed to be a[10], why there is length? Array object in javascript has length, but is index type an array? If so, why the above example defines a length? Is it necessary?
Sorry for my rant. You can see I am very confused.

Second,

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? The indexer is like a[10] = "Tom", then what is the subtype of indexer?

Answer

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 ^

Comments