简体   繁体   English

尝试访问TypeScript词典时出现“不支持的索引器”

[英]“Unsupported indexer” when trying to access a TypeScript dictionary

I'm trying to make a Minecraft MakeCode extension in TypeScript and a dictionary is needed to map a string to a corresponding string: 我正在尝试在TypeScript中进行Minecraft MakeCode扩展,并且需要字典来将字符串映射到相应的字符串:

const chars:{[index:string]:string} = {
  "A": "MSOJOQJ",
  "B": "JWIQWIQ"
  // ...
};

However when I try to look up a value of the dictionary: 但是,当我尝试查找字典的值时:

let look = chars["A"];

TypeScript throws an error that it is unsupported indexer . TypeScript抛出一个错误,它是unsupported indexer

Setting the key-value pairs for the dictionary doesn't work either: 设置字典的键/值对也不起作用:

chars["C"] = "HIHWQHQ"; // unsupported indexer

Is there any fault in my code or is TypeScript bugged/too strict? 我的代码中是否有任何错误,或者TypeScript错误/过于严格?

After further looking into the MakeCode environment, it appears that while it doesn't support dictionary indexers on mapped types, it does support dot access: 在进一步研究MakeCode环境之后,似乎它虽然不支持映射类型的字典索引器,但它确实支持点访问:

const dicto: { [key: string]: string } = {
    hello: "world",
    goodbye: "friends",
};

dicto["hello"] = "wow!"; // error
const b = dicto["goodbye"]; // error

dicto.hello = "wow!"; // ok
const c = dicto.goodbye; // ok, c inferred to be of type string

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM