首页 > 解决方案 > 打字稿:在“{}”类型上找不到带有“字符串”类型参数的索引签名

问题描述

所以我有以下对象:

{"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]"
  }
}    

有人可以帮帮我吗?

标签: typescript

解决方案


这是无效的 {"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" } }

尝试这个

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

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

// make the Realm database Result Object a plain "normal" object
let plainObjectResult: any = { "1": { "name": "spencer", "number": "965756" }, "2": { "name": "mary", "number": "5346" }, "3": { "name": "john", "number": "1234" } };

const resultArray: PersonResults[] = [];

if (Object.keys(plainObjectResult).length > 0) {
  for (let person in plainObjectResult) {
    let id = '' + person;
    let obj:PersonResults  = {};
    obj[id] = plainObjectResult[person];
    resultArray.push(obj); // above error occurs for "plainObjectResult[person]"
  }
}

console.log('resultArray: ', resultArray)

推荐阅读