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": {"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)
推荐阅读
- python - python3.6支持的库函数是否也被python3.7支持?
- c++ - 在 C++ 中打印时只显示一个字符
- javascript - 在没有不必要空格的情况下替换句子中的单词?
- c# - 没有流的 Image.FromFile 内存不足
- django - 如何在 django-tables2 的列前添加空格和 $
- java - 内存数据库中的 H2 在列名和我想使用的值之间感到困惑
- java - Eclipse 4-10 64bit:无法解析 SWT 库
- reactjs - React Native - 在 WebView 中设置 localStorage
- django - 有什么区别:Django,Apache,AWS
- c++ - 矢量如何找到第一个和最后一个当前值