0

I have a TypeScript project where I am trying to extract data from a properties file but it shows me the following error that I cannot resolve in the getProperty[codProduct.toUpperCase()] code:

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

This is my function:

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);
        }
    }
}

This is my properties file:

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

This is the models.ts:

interface ListProductBatchModel {
    resp: ResultMsg
}

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

export { ListProductBatchModel, ResultMsg };
menphis
  • 85
  • 1
  • 8

1 Answers1

0

The error you're seeing means that typescript has determined that the type of getProperty is {} (an empty object).

Because it's empty, typescript is warning that you cannot access any field on it by string, as there are no fields to access.

In the eyes of typescript, your code is equivalent to:

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

To resolve this issue getProperty will need a proper type.
How this should be typed will determine on your project setup.

Stanislas
  • 1,893
  • 1
  • 11
  • 26
  • But I still don't understand why this happens or how can I solve it? I don't understand why it gets empty if the json has data – menphis Nov 13 '21 at 19:38
  • 1
    There are a few ways to resolve this. A common approach you'll find is to create a `typings.d.ts` file with `declare module "*.json" { ... }` which describes what the json contains. However a better approach might be to use the [resolveJsonModule](https://www.typescriptlang.org/tsconfig#resolveJsonModule) setting in your tsconfig. See https://stackoverflow.com/questions/49996456/importing-json-file-in-typescript or https://stackoverflow.com/questions/65775338/importing-json-as-a-type. – Stanislas Nov 14 '21 at 00:04