Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
            }
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading