Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何正确地向对象添加索引签名_Javascript_Typescript_Ecmascript 6_Index Signature - Fatal编程技术网

Javascript 如何正确地向对象添加索引签名

Javascript 如何正确地向对象添加索引签名,javascript,typescript,ecmascript-6,index-signature,Javascript,Typescript,Ecmascript 6,Index Signature,我有以下错误(解决方案正在运行): 元素隐式具有“any”类型,因为类型“{}”没有索引 签名。[7017] 代码: 我尝试添加接口而不是对象(可能是错误的),比如-jsonObject:IProps。但这并没有帮助,因为我的对象(jsonObject参数)看起来是这样的: success: string error: string [propName: string]: string 或 因此对象结构不同。 所以我很想知道如何解决这种情况下的无索引签名错误 它看起来像你想要的吗

我有以下错误(解决方案正在运行):

元素隐式具有“any”类型,因为类型“{}”没有索引 签名。[7017]

代码:

我尝试添加接口而不是对象(可能是错误的),比如-
jsonObject:IProps
。但这并没有帮助,因为我的对象(jsonObject参数)看起来是这样的:

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

这不是此代码的解决方案,因为jsonObject可以是JSONObj或NamesObj类型,也可以是另外两个不同的对象。它们都具有相同的属性[propName:string]:string@Marta那你就把它变成一个联盟。请参阅更新的答案。是的-谢谢,这正是我所需要的。这么简单的解决方案,我花了好几个小时already@Marta很高兴我能帮忙!
  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],
      }
    })
  }