Sometimes, we want to use the for-of loop with index and key with TypeScript.
In this article, we’ll look at how to use the for-of loop with index and key with TypeScript.
How to use the for-of loop with index and key with TypeScript?
To use the for-of loop with index and key with TypeScript, we call the array’s entries
method to return an array with arrays of the array index and the corresponding value of each entry.
For instance, we write
for (const [index, item] of someArray.entries()) {
//...
}
to call someArray.entries
to return an array with each entry of it being an array of the array entry’s index
and the corresponding item
.
We destructure that to get the index
and item
so we can use them in the loop body.
Conclusion
To use the for-of loop with index and key with TypeScript, we call the array’s entries
method to return an array with arrays of the array index and the corresponding value of each entry.