Home > OS >  Type must have a '[Symbol.iterator]()' method that returns an iterator
Type must have a '[Symbol.iterator]()' method that returns an iterator

Time:01-29

I am using this code to iterate through a custom object:

interface TableItemBody {
    [fieldId: string]: string
}

interface TableItem {
    [tabId: string]: TableItemBody | TableItemBody[]
}

const iterate = (entry: TableItem) => {
    for (const tabId of Object.keys(entry)) {
        if (Array.isArray(entry[tabId])) {
            for (const idx of entry[tabId]) {
                for (const fieldId of Object.keys(entry[tabId][idx])) {
                    console.log(fieldId)
                }
            }
        } else {
            for (const fieldId of Object.keys(entry[tabId])) {
                console.log(fieldId)
            }
        }
    }
}

const tableItem: TableItem = {
    tab1: {
        field1: 'fieldValue'
    },
    tab2: [{
        field2: 'fieldValue'
    }]
}

iterate(tableItem)

However, I am getting two errors. The first one is Type 'TableItemBody | TableItemBody[]' must have a '[Symbol.iterator]()' method that returns an iterator. I am using Array.isArray(entry[tabId]) to ensure that I am actually iterating through an array. So why does this error appear?

If you want to play with that code, here is the link the to typescript playground.

CodePudding user response:

You need to cast it to TableItemBody[]. Look here

const iterate = (entry: TableItem) => {
    for (const tabId of Object.keys(entry)) {
        if (Array.isArray(entry[tabId])) {
            const tableItems = entry[tabId] as TableItemBody[]
            for (const tableItem of tableItems) {
                for (const fieldId of Object.keys(tableItem)) {
                    console.log(fieldId)
                }
            }
        } else {
            for (const fieldId of Object.keys(entry[tabId])) {
                console.log(fieldId)
            }
        }
    }
}
  •  Tags:  
  • Related