如何在具有键值对的类型脚本中创建可迭代类型

how to make an iterable type in type script that has a key value pair

我正在使用类型脚本,我想创建一个类型来表示这样的对象 生成的密钥是动态生成的我该怎么做

{  dog:true,
cat:true,
x:true
}

目前我正在使用 any 但我想要一个合适的类型

 const matches: any= {}

当我尝试使用

时出现这个错误

 {[key: string]: boolean}
Type 'string[] | { [key: string]: boolean; }' must have a '[Symbol.iterator]()' method that returns an iterato

导致此错误的代码

const docgetter=()=>
    const matches: { [key: string]: boolean } = {}
    const documentFieldKeys = Array.isArray(documentNames) ? documentNames : Object.keys(documentNames)
  

    return [matches, documentFieldKeys]

}



const [matches,kycKeys]=docgetter()

for(key of kycKeys)

使用[key : string]

type dict = {
    [key : string] : boolean
}

const o: dict = {
    cat: true,
    dog: true,
    x: false
}

编辑:

您没有为 docgetter 的输出指定类型,因此打字稿将其错误地推断为

const kycKeys: {
    [key: string]: boolean;
} | string[]

您可以通过

来解决这个问题
for(const key of kycKeys as string[]) {
  console.log(key)
}

让打字稿知道你正在迭代一个数组而不是一个对象(对象会出错)

或者你可以让打字稿知道输出是什么

您的代码的固定版本:

const documentNames = {
  "a": true,
  "b": true,
  "c": true
}

type output = [
  { [key: string]: boolean },
  string[]
]

const docgetter=() : output => {
    const matches: { [key: string]: boolean } = {}
    const documentFieldKeys : string[] = Array.isArray(documentNames) ? documentNames : Object.keys(documentNames)
    return [matches, documentFieldKeys]

}


const [matches,kycKeys]=docgetter()

for(const key of kycKeys) {
  console.log(key)
}