以下編譯和運行很好。但在我看來,接口聲明指出索引應該是類型編號。但我在這裏使用了一個字符串。這應該是一個編譯錯誤?
是否有我沒有收到編譯錯誤的原因?
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'."
如果索引簽名與對象字面值中的屬性賦值不匹配,則假定它與實際屬性不匹配,則會在沒有上下文類型的情況下處理它(忽略而不出錯)。