注意在此示例中,m是字符串|数字 - 这是因为JavaScript对象键始终被强制为字符串,因此OBJ [0]始终与OBJ [“ 0”]。
我的问题是为什么
number
boolean
?为什么不或
object
string
?
typescript支持
number
和
symbol
index签名string
和
symbol
键,因此Typescript中的the the the the the the the
string
,symbol
,模板和模式模板文字(是string
的子类型)索引签名应该是完全合理的。 但是number
?? 数字索引签名专门旨在支持
arrays和其他类似阵列的对象。 如果用数字索引索引到数字索引产生的打字稿错误,那将是非常烦人的:
const arr = ["a", "b", "c"];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i].toUpperCase());
// -----------> ~ <-- error, you can't index with a number?
}
quirequiring like like like like the Idiomant JavaScript会带来不便。 而且它甚至无济于事;编译器无法真正分辨出arr[String(i)]
和任何其他字符串之间的区别,因此它不明白String(1)
arr[String(1)]
的方法。
因此,即使对象没有真正具有
arr["pop"]
值键,typeScriptpretends
为了更自然地支持数组,因为数组非常常用于惯用的Javascript代码中的数字索引。
另一方面,没有人用其他对象将JavaScript对象索引,或者使用
number
键:
boolean
well,也许不是nobody,但是很少见,以至于像
// nobody does this
const foo = { true: 1, false: 0, "[object Object]": 2 };
console.log(foo[Math.random() < 0.5]) // what
console.log(foo[{ a: 123 }]); // what are you doing
或
foo[false]
这样的代码比预期的代码更有可能是编程错误。 因此,打字稿没有理由允许foo[{}]
或boolean
有关更多信息。
to代码的链接链接