【发布时间】:2021-10-24 14:12:23
【问题描述】:
我有一个 Typescript 函数,我在其中根据变量从 JSON 对象读取数据,但在访问属性时它显示错误。
这是我的代码:
let codCountry = 'CO';
let countryId = {
"CO": "fileIdCo",
"ES": "fileIdEs",
"MX": "fileIdMx"
};
let fileId;
for (let getCod of Object.keys(countryId)) {
if (getCod == codCountry) {
fileId = countryId[getCod] // error
}
}
这是我在countryId[getCod] 中遇到的错误:
The element has an "any" type implicitly because the expression of type "string" cannot be used to index the type "{CO: string; ES: string; MX : string;} ".
No index signature was found with a parameter of type "string" in type "{CO: string; ES: string; MX: string;}"
【问题讨论】:
-
就像你问的那样:如果你登录 countryId.CO 你会得到'fileIdCo'。
-
您的代码在在线编译器上运行良好:onecompiler.com/javascript/3x9e67nbj
-
@fatimasajjad 那是因为它是打字稿错误。
-
@Terry 没错,你知道在这种情况下会出现什么问题吗?我无法修复它
标签: arrays json typescript