javascript - 如何正确地将索引签名添加到对象
问题描述
我有以下错误(解决方案有效):
元素隐式具有“任何”类型,因为类型“{}”没有索引签名。[7017]
代码:
const createCollection = (jsonObject: object, namesObject: object): INameHex[] => {
return Object.keys(jsonObject).map(itemKey => {
return {
name: namesObject[itemKey],
hex: jsonObject[itemKey],
}
})
}
我尝试添加接口而不是对象(可能不正确),例如 - jsonObject: IProps
。但这无济于事,因为我的对象(jsonObject 参数)看起来像这样:
success: string
error: string
[propName: string]: string
或者
default: string
[propName: string]: string
所以对象结构不同。所以我真的很想知道在这种情况下如何解决没有索引签名错误?
解决方案
它看起来像你想要的吗?
interface JSONObj {
success: string
error: string
[propName: string]: string // this is an index signature
}
interface NamesObj {
default: string
[propName: string]: string // this is an index signature
}
const createCollection = (jsonObject: JSONObj | NamesObj, namesObject: NamesObj): INameHex[] => {
return Object.keys(jsonObject).map(itemKey => {
return {
name: namesObject[itemKey],
hex: jsonObject[itemKey],
}
})
}
它不会产生任何错误,并且从 POV 类型来看是完全正确的。
推荐阅读
- java - 解析没有包装类的 JSON 数组
- ios - 解码具有动态密钥的 JSON
- xamarin.forms - Xamarin.Forms 如何在录音/播放时显示进度指示器
- python - python中k-means聚类算法中处理分类数据的方法
- jquery - AJAX 在条件下运行
- ios - iOS:相机胶卷目录 xamarin
- javascript - 从Javascript上的字符串中提取键:值对与正则表达式相关联
- javascript - 循环遍历对象的 JSON 数组并根据对象的匹配 ID 获取属性
- python - 首先基于属性和距离矩阵对观测值进行聚类
- xamarin.android - Oxyplot 图形占据整个屏幕显示