【问题标题】:The element has a type "any" implicitly because the expression of type "string" cannot be used to index the type {}元素隐含类型为“any”,因为类型“string”的表达式不能用于索引类型 {}
【发布时间】:2021-12-24 17:44:44
【问题描述】:

我有一个 TypeScript 项目,我试图从属性文件中提取数据,但它显示了以下错误,我无法在 getProperty[codProduct.toUpperCase()] 代码中解决:

The element has a type "any" implicitly because the expression of type "string" cannot be used to index the type {}

这是我的功能:

import * as logger from 'winston';
import * as getProperty from '../json/product.json';
import { ListProductBatchModel, ResultMsg } from '../models/listProduct.models';

export class ListProductBatchUtils {
    
    public async getDataProduct(codProduct: string): Promise<ListProductBatchModel> {
        try {
            let result: ResultMsg;
            if (getProperty[codProduct.toUpperCase()]) {
                result = {
                    name: getProperty[codProduct.toUpperCase()].name,
                    price: getProperty[codProduct.toUpperCase()].price
                }
            }else {
                result = {
                    error: "ERROR"
                }
            }
            logger.info('start')
            return Promise.resolve({ resp: result });
            
        } catch (error) {
            logger.info(JSON.stringify(error));
            return Promise.reject(error);
        }
    }
}

这是我的属性文件:

{
    "CT": {
        "name": "car",
        "price": "5,00"
    },
    "CC": {
        "name": "box",
        "price": "6,00"
    }
}

这是models.ts:

interface ListProductBatchModel {
    resp: ResultMsg
}

interface ResultMsg {
    name?: string,
    price?: string,
    error?: string
}

export { ListProductBatchModel, ResultMsg };

【问题讨论】:

    标签: arrays json typescript properties


    【解决方案1】:

    您看到的错误意味着打字稿已确定getProperty 的类型是{}(一个空对象)。

    因为它是空的,打字稿警告你不能通过字符串访问它上面的任何字段,因为没有字段可以访问。

    在打字稿看来,你的代码相当于:

    const instance = {};
    instance["field"]; // Error: since there is no field on instance
    

    要解决此问题,getProperty 需要正确的类型。
    应如何键入将取决于您的项目设置。

    【讨论】:

    猜你喜欢
    • 2021-10-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
    相关资源
    最近更新 更多