typescript - 元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于在 angularjs 中进行索引
问题描述
***元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“{}”在“{}”类型上找不到参数类型为“字符串”的索引签名
并且还显示对象可能是未定义的。
我试图在打字稿文件中实现此代码,但它显示了这些错误。为什么?我无法找到错误。请帮忙。
getGlobalData() {
return this.http.get(this.globalDataUrl, { responseType: 'text' }).pipe(
map(result => {
let data: GlobalDataSummary[] = [];
let raw = {}
let rows = result.split('\n');
rows.splice(0, 1);
// console.log(rows);
rows.forEach(row => {
let cols = row.split(/,(?=\S)/)
let cs = {
country: cols[3],
confirmed: +cols[7],
deaths: +cols[8],
recovered: +cols[9],
active: +cols[10],
};
let temp: GlobalDataSummary = raw[cs.country];
if (temp) {
temp.active = cs.active + temp.active
temp.confirmed = cs.confirmed + temp.confirmed
temp.deaths = cs.deaths + temp.deaths
temp.recovered = cs.recovered + temp.recovered
raw[cs.country] = temp;
} else {
raw[cs.country] = cs;
}
})
return <GlobalDataSummary[]>Object.values(raw);
})
)
}
解决方案
“字符串”类型的表达式不能用于索引类型“{}”
这意味着你不能这样做{}['somePropertyName']
。那是因为您的raw
变量没有显式类型,并且您的代码将其初始化为{}
,一个没有属性索引器的空对象。
您可以提供raw
一种类型,允许您的代码通过字符串索引获取其属性,如下所示:
let raw: {
[key: string]: any
};
推荐阅读
- video-streaming - 媒体流:打包时
- xcode - 在 React Native 应用程序中为 Fabric crashlytics 日志添加导入文件后,在 Xcode 中找不到 RCTLog.h 文件错误
- algorithm - 协助计算调用其他函数的函数的时间复杂度
- visual-studio - “未配置 NDK。” 在 Visual Studio 代码中
- c# - 我可以在哪里存储用户在 c# 中提供的连接字符串?
- regex - 在postgres中的正则表达式匹配后从列中提取信息
- firebase - Firestore 快照侦听器 - fromCache 值不一致
- python - 从具有 2 个公共键的字典列表中构建新字典的最有效方法?
- asp.net-core - Web Api 中是否可以使用 DuplicatePropertyNameHandling?
- r - 一次合并两个以上的数据帧