我正在通过TypeScript

问题描述 投票:0回答:1
他们给出了以下解释:

注意在此示例中,m是字符串|数字 - 这是因为JavaScript对象键始终被强制为字符串,因此OBJ [0]始终与OBJ [“ 0”]。

我的问题是为什么
number

boolean
?为什么不

object

string

	
typescript支持
number
symbol

index签名
typescript
1个回答
4
投票
。 JavaScript中的对象确实只有

string

symbol
键,因此Typescript中的the the the the the the the
stringsymbol,模板和模式模板文字(是
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"]
值键,typeScript
pretends

为了更自然地支持数组,因为数组非常常用于惯用的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
索引签名。请参阅“所有法律JavaScript都是合法的字样”是什么意思?

有关更多信息。

to代码的链接链接

	

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.