Should this give a compilation error?

The following compiles and works fine. But it seems to me that the interface declaration says that the index should have a type number. But instead, I use a string.

Is there a reason why I am not getting a compilation error?

interface Dictionary {
[index: number] : string;
}

var dictionary : Dictionary = {};
dictionary["First"] = "apple";

console.log(dictionary["First"]);
+3
source share
1 answer

This is a subtle thing about indexes. When using an interface with an index signature, for example:

[index: number] : string

This means that at any time when an index exists number, it must be set to a value string. It does not limit the instance of the object to only numbers. When there is a number, it should be set to string.

From the specification (3.7.4. Index Signatures Currently):

, , . , T, T.

:

[index: number]: number;

:

dictionary[1] = "apple";

: "Cannot convert 'string' to 'number'."

, ( ), .

+4

All Articles