簡體   English   中英

嘗試訪問TypeScript詞典時出現“不支持的索引器”

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

我正在嘗試在TypeScript中進行Minecraft MakeCode擴展,並且需要字典來將字符串映射到相應的字符串:

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

但是,當我嘗試查找字典的值時:

let look = chars["A"];

TypeScript拋出一個錯誤,它是unsupported indexer

設置字典的鍵/值對也不起作用:

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

我的代碼中是否有任何錯誤,或者TypeScript錯誤/過於嚴格?

在進一步研究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