打字稿:在“ {}”类型上找不到带有“字符串”类型参数的索引签名

时间:2020-03-02 07:40:57

标签: typescript

所以我有以下对象:

{"1": {"name": "spencer", "number": "965756"}}, {"2": {"name": "mary", "number": "5346"}},  {"3": {"name": "john", "number": "1234"}}

该对象是数据库查询的结果,我想使用array.push()方法将此对象转换为数组。这给出了错误:

error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
  No index signature with a parameter of type 'string' was found on type '{}'.

我非常确定会发生错误,因为如果数据库查询失败,'{}'将是空对象。因此,在将结果对象(plainObjectResult)转换为数组之前,我进行了检查。但是错误仍然存​​在,我不知道为什么。

这是代码:

export interface Person {
  name: string;
  number: string;
}

export interface PersonResults {
  [key: string]: Person;
}

// make the Realm database Result Object a plain "normal" object
const plainObjectResult: object = realmToPlainObject(queryResult);

const resultArray: PersonResults[] = [];

if (Object.keys(plainObjectResult).length > 0) {
  for (let person in plainObjectResult) {
    // person: 0, 1, 2, ...
    // plainObjectResult[person]: {"name": "spencer", "number": "965756"}
    resultArray.push({[person]: plainObjectResult[person]}); // above error occurs for "plainObjectResult[person]"
  }
}    

有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

这是无效 \n

应该 {"1": {"name": "spencer", "number": "965756"}}, {"2": {"name": "mary", "number": "5346"}}, {"3": {"name": "john", "number": "1234"}}

尝试一下

{ "1": { "name": "spencer", "number": "965756" }, "2": { "name": "mary", "number": "5346" }, "3": { "name": "john", "number": "1234" } }