以下编译和运行很好。但在我看来,接口声明指出索引应该是类型编号。但我在这里使用了一个字符串。这应该是一个编译错误?
是否有我没有收到编译错误的原因?
interface Dictionary {
[index: number] : string;
}
var dictionary : Dictionary = {};
dictionary["First"] = "apple";
console.log(dictionary["First"]);
以下编译和运行很好。但在我看来,接口声明指出索引应该是类型编号。但我在这里使用了一个字符串。这应该是一个编译错误?
是否有我没有收到编译错误的原因?
interface Dictionary {
[index: number] : string;
}
var dictionary : Dictionary = {};
dictionary["First"] = "apple";
console.log(dictionary["First"]);
这是关于索引签名的微妙之处。当使用接口与索引签名等:
[index: number] : string
这意味着,任何时候有这是一个number
,它必须被设置为一个值string
的索引。它不会将对象实例仅限于number
s。有数字时,必须设置为string
。
从规范(3.7.4指数目前签名):
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.
如果你要改变接口:
[index: number]: number;
,并添加一行:
dictionary[1] = "apple";
会出现编译错误:"Cannot convert 'string' to 'number'."
如果索引签名与对象字面值中的属性赋值不匹配,则假定它与实际属性不匹配,则会在没有上下文类型的情况下处理它(忽略而不出错)。