为什么Typescript Map不能像可索引types那样自动索引(&property-accessable)?
所以,在打字稿下面的代码作品:
interface CounterArray { [index: string]: number; } let myArray: CounterArray = {}; myArray["001"] = 0 myArray["002"] = 0 console.log(myArray[0]) // should result 0
得到它了。 都好! 但是,如果我做类似的地图。
const map = new Map map.set("001",0) map.set("002",0) console.log(map[0]) // Syntax error: Element implicitly has an 'any' type because type 'Map' has no index signature.
那么我对此非常困惑,因为来自Java / Kotlin / C#,默认情况下Map应该可以通过键索引。 我认为,这样的工作应该使用Map
来优雅地完成。
而且,使用“上面的第一个代码块”,我可以做这样的事情:
console.log(myArray["001"]++) // Should results 1
虽然我不能在地图上做这样的事情
console.log(myArray.get("001")++) // Syntax error, Object is possibly undefined -> on editor level. So it's a syntax error. Not compile or other runtime error.
我觉得这种行为很奇怪。 或者也许是预期的? 也许我知道的Map
(来自Java / C#/ Kotlin)与typescript的Map
不同?
感谢您的解释!