typescript定义一个具有n个键/值的对象

时间:2018-04-12 20:59:24

标签: json typescript interface

我是Typescript的新手,我想为以下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"
            }
         }
      }
   }
}

以下是我当前定义界面的方式,对象asianamerican可以包含n个键值。我对定义它的语法感到困惑。有人可以指导我如何解决这个问题。谢谢你的阅读。

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

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

1 个答案:

答案 0 :(得分:1)

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

这里我告诉打字稿,亚洲人是一张带有key = string和value = string的地图。