Aniks
Aniks

Reputation: 1131

typescript define an object with n number of key/values

I am new to Typescript and I would like to define interfaces for the following JSON:

{  
   "company":"abc inc",
   "logoUrl":"someUrl",
   "phone":"1234567890",
   "branch":{  
      "nyc":{  
         "products":{  
            "asian":{  
               "somekey1":"someValue1",
               "somekey2":"someValue2",
               "somekeyN":"somevalueN"
            },
            "american":{  
               "somekey1":"someValue1",
               "somekey2":"someValue2",
               "somekeyN":"somevalueN"
            }
         }
      },
      "boston":{  
         "products":{  
            "asian":{  
               "somekey1":"somevalue1",
               "somekey2":"somevalue2",
               "somekeyN":"somevalueN"
            },
            "american":{  
               "somekey1":"somevalue1",
               "somekey2":"somevalue2",
               "somekeyN":"somevalueN"
            }
         }
      }
   }
}

Here is how I have currently defined my interfaces, the object asian and american can contain n number of key values. I am confused with the syntax for defining it. Can someone please guide me how I should go about this. Thanks for reading.

interface Products {
    asian: {};
    american: {};
}

interface Configuration {
    company: string;
    phone: string;
    logoUrl: string
    branch: {
      nyc: {
        products: Products;
      };
      boston: {
         products: Products;
      };
    };
}

Upvotes: 1

Views: 1589

Answers (1)

Daniel
Daniel

Reputation: 1953

interface Products {
    asian: {[key: string]: string};
    american: {[key: string]: string};
}

Here I am telling typescript, that asian is a map with key = string and value = string.

Upvotes: 6

Related Questions