首页 > 解决方案 > 如何正确地将索引签名添加到对象

问题描述

我有以下错误(解决方案有效):

元素隐式具有“任何”类型,因为类型“{}”没有索引签名。[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

所以对象结构不同。所以我真的很想知道在这种情况下如何解决没有索引签名错误?

标签: javascripttypescriptecmascript-6index-signature

解决方案


它看起来像你想要的吗?

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 类型来看是完全正确的。


推荐阅读