Search code examples
typescripttypescript-typingsreact-typescript

TypeScript, type for json response Object in Object[]


I have the response from API. I need processing that response and get values from that. I can understand which type I should use for that. Also when I tried this.filters[key] I fetched error

Element implicitly has an 'any' type because index expression is not of type 'number'.ts(7015)

My object from response:

"OneType": {
    "OnePart": {
        "Values": [
            "codes..",
            "codes..",
            "codes..",
            "codes.."
        ],
        "Values2": [
            "codes..",
            "codes..",
            "codes..",
            "codes.."
        ]
    },
    "SecondPart": {
        "Values": [
            "codes..",
            "codes..",
            "codes..",
            "codes.."
        ],
        "Values2": [
            "codes..",
            "codes..",
            "codes..",
            "codes.."
        ]
    }
}

I tried make type, but still have a error about key.

type FilterArray = { [key: string]: [] };

The error in VSCode

I want to note that each value can have multiple values, like the first one (OneType, TwoType...) and (FirstPart / Second/ third..)


Solution

  • So, I found the solution. Everything can be easy.

    We make JSON type and if we want to get an object by key we can use:

    type JSONValue =
        | string
        | number
        | boolean
        | JSONObject
        | JSONArray;
    
    interface JSONObject {
        [x: string]: JSONValue;
    }
    
    interface JSONArray extends Array<JSONValue> { }
    
    

    Receive:

    const myObject: JSONArray = {
     first: {
         second: {
           third: ['1','2']
         }, 
         secondSecond: {
           ...
         },
       ...
     }
    };
    const result = myObject[key as keyof JSONValue];