Greg Gum
Greg Gum

Reputation: 38109

Should this be giving a compile error?

The following compiles and runs just fine. But it seems to me that the interface declaration says that the index should be of type number. But I use a string here instead.

Is there a reason I don't get a compile error?

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

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

console.log(dictionary["First"]);

Upvotes: 3

Views: 370

Answers (1)

WiredPrairie
WiredPrairie

Reputation: 59793

This is a subtle thing about the index signatures. When using an interface with an index signature like:

[index: number] : string

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

From the specification (3.7.4 Index Signatures currently):

Numeric index signatures, specified using index type number, define type constraints for all numerically named properties in the containing type. Specifically, in a type with a numeric index signature of type T, all numerically named properties must have types that are subtypes of T.

If you were to change the interface to:

[index: number]: number;

And add a line:

dictionary[1] = "apple";

There will be a compile error: "Cannot convert 'string' to 'number'."

If the index signature doesn't match the property assignment in an object literal, it is processed without a contextual type (ignored without error), assuming it didn't match an actual property.

Upvotes: 4

Related Questions