Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 使用基于字符串的键的对象数组的类型声明?_Typescript - Fatal编程技术网

Typescript 使用基于字符串的键的对象数组的类型声明?

Typescript 使用基于字符串的键的对象数组的类型声明?,typescript,Typescript,My web service返回如下所示的对象数组: [ { "abc": "test 1" }, { "def": "test 2" }, { "ghi": "test 3" } ] 现在我想为这个结果声明一个TypeScript接口。但是我不知道怎么做,因为每个对象的键可以是名称不同的字符串 具体而言: 一个对象只有一个属性。

My web service返回如下所示的对象数组:

[ 
  {
   "abc": "test 1"
  },
  {
   "def": "test 2"
  },
  {
   "ghi": "test 3"
  }
]
现在我想为这个结果声明一个TypeScript接口。但是我不知道怎么做,因为每个对象的键可以是名称不同的字符串

具体而言:

一个对象只有一个属性。 该属性的键可以有任何名称。 属性的值是一个字符串。
根据您提供的代码,我建议使用:

const a: { [key: string]: string }[] = [ 
  {
   "abc": "test 1"
  },
  {
   "def": "test 2"
  },
  {
   "ghi": "test 3"
  }
]

它是一个带有字符串值的字符串索引对象。

根据您提供的代码,我建议使用:

const a: { [key: string]: string }[] = [ 
  {
   "abc": "test 1"
  },
  {
   "def": "test 2"
  },
  {
   "ghi": "test 3"
  }
]

它是一个具有字符串值的字符串索引对象。

可能不是最佳解决方案,如果您严格要求接口:

interface webResponse{
    [key: string]: string;
}

let myvalue= new Array<webResponse>();

myvalue[0] = {["asdas"]: 'qwerty'};
myvalue[1] = {["asdas2"]: 'qwerty2'};

您可以使用simple for..in.

迭代myvalue,这可能不是最好的解决方案,以防您严格要求接口:

interface webResponse{
    [key: string]: string;
}

let myvalue= new Array<webResponse>();

myvalue[0] = {["asdas"]: 'qwerty'};
myvalue[1] = {["asdas2"]: 'qwerty2'};

您可以使用simple for..in.

来迭代myvalue,这意味着Object[]?可以为此编写更具体的类型,但我们没有足够的详细信息来准确地说明。您给出的示例的哪些部分可以变化,哪些部分是固定的?钥匙总是那三把吗?对象总是只有一个关键点吗?对象中的值总是字符串吗?试着在你的问题中用简单的英语发布一个类型的规范,然后也许有人可以过来把它转换成Typescript。在Typescript手册中,请参阅。这意味着Object[]?可以为此编写一个更具体的类型,但我们没有足够的细节来准确地说明。您给出的示例的哪些部分可以变化,哪些部分是固定的?钥匙总是那三把吗?对象总是只有一个关键点吗?对象中的值总是字符串吗?试着在你的问题中用简单的英语发布一个类型说明,然后也许有人可以过来把它转换成Typescript。在Typescript手册中,请参阅。也可以使用Record[]也可以使用Record[]