【问题标题】:The element has a type "any" implicitly because the expression of type "string" cannot be used to index the type元素隐含类型为“any”,因为“string”类型的表达式不能用于索引该类型
【发布时间】: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


【解决方案1】:

问题来自Object.keys(countryId) 返回string[] 而不是countryId 上可用的键数组。这可以通过强制转换 Object.keys() 返回的内容来解决,以确保它是对象上的键数组,即:

for (let getCod of Object.keys(countryId) as Array<keyof typeof countryId>) {
    if (getCod == codCountry) {
        fileId = countryId[getCod]
    }
}

现在你可能会问,keyof typeof countryId 究竟是什么意思?

  • typeof 返回countryId 对象的类型
  • keyof 返回 countryId 对象的 type 上所有可用的键

See proof-of-example on TypeScript Playground.


如果您不想一直执行此手动转换,您甚至可以将其抽象为为您执行此操作的方法:

function getObjectKeys<T extends object>(obj: T) {
    return Object.keys(obj) as Array<keyof typeof obj>;
}

那么就是使用getObjectKeys(YOUR_OBJECT)而不是直接使用Object.keys

for (let getCod of getObjectKeys(countryId)) {
    if (getCod == codCountry) {
        fileId = countryId[getCod]
    }
}

See improved example on TypeScript Playground.

【讨论】:

    【解决方案2】:

    定义接口

    interface CC {
        CO: string;
        ES: string;
        MX: string;
    }
        let cod = 'CO';
    
        let countryId:<CC> = {
            "CO": "fileIdCo",
            "ES": "fileIdEs",
            "MX": "fileIdMx"
        };
    

    【讨论】:

    • 请删除这个答案,因为它对这个问题没有帮助。我已经更新了问题。
    猜你喜欢
    • 2021-12-24
    • 2020-11-14
    • 2022-11-10
    • 2022-01-17
    • 2019-11-24
    • 2022-10-08
    • 2023-01-09
    • 1970-01-01
    • 2022-10-23
    相关资源
    最近更新 更多