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

Time:05-08

I am using type script and I want to make a type that represents an object like this the keys generated are genrated dynamically how do I do that

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

currently I am just using any but I woud like a proper type

 const matches: any= {}

i get this error when i try to use


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

code that causes this error

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)

CodePudding user response:

Using [key : string]

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

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

Edit:

you didn't specify a type for the output of docgetter so typescript inferred it incorrectly as

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

You could either fix this by doing

for(const key of kycKeys as string[]) {
  console.log(key)
}

to let typescript know you are iterating an array and not an object (object would error)

Or you could let typescript know what the output is

fixed version of your code:

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)
}
  • Related