Search code examples
javascripttypescriptecmascript-6index-signature

How to properly add index signature to object


I have following errors (solution is working):

Element implicitly has an 'any' type because type '{}' has no index signature. [7017]

Code:

const createCollection = (jsonObject: object, namesObject: object): INameHex[] => {
  return Object.keys(jsonObject).map(itemKey => {
    return {
      name: namesObject[itemKey],
      hex: jsonObject[itemKey],
    }
  })
}

I tried adding interface instead of object (maybe incorrectly), something like - jsonObject: IProps. But it is not helping since my object (jsonObject argument) looks like that:

  success: string
  error: string
  [propName: string]: string 

or

  default: string
  [propName: string]: string

so the object structure differs. So I would really like to know how to resolve no index signature error in this scenario?


Solution

  • Does it look like what you want?

    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],
          }
        })
      }
    

    It produces no errors and is perfectly correct from the types POV.