I'm trying to loop through an object which holds a number of properties and the value is always an array of numbers. When I try to run the code below I get the error:
property 'length' does not exist on type 'unknown'
When using Typescrip how do I assign a types when the object key/value pair is destructured in this way?
Thanks
for (const [key, value] of Object.entries(object)) {
console.log(value.length)
}
You can add a type to the object beforehand.
const object: Record<string, number[]> = {}
for (const [key, value] of Object.entries(object)) {
console.log(value.length)
}
Read more about the Record utility type here
You can also type cast the object instead.
for (const [key, value] of Object.entries(object as Record<string, number[]>)) {
console.log(value.length)
}
See all the examples in TS playground here